[prev in list] [next in list] [prev in thread] [next in thread] 

List:       groovy-user
Subject:    empty ranges
From:       "Martin C. Martin" <martin () metahuman ! org>
Date:       2005-06-18 22:42:20
Message-ID: 42B4A34C.9060909 () metahuman ! org
[Download RAW message or body]

Hi,

I have a list x, and I want to compute the difference between adjacent 
elements.  In other words, I want a new list y, one element shorter than 
x, such that y[i] = x[i+1] - x[i].

If x has at least two elements, I can do this:

def y = (0 ..< (x.size() - 1)).collect { x[it+1] - x[it] }

But if it has 1 or 0, that fails.

This is the long complained about problem with reverse ranges.  It 
hasn't been fixed in over a year of on-again-off-again complaining, 
including a through discussion of possible options.  So, assuming it's 
not going to be fixed, what are my options?  The obvious one is to wrap 
it in an if:

def y
if (x.size() >= 2) {
    y = (0 ..< (x.size() - 1)).collect { x[it+1] - x[it] }
} else {
    y = []
}

But that's pretty verbose, and it's easy to forget the if, since it 
deals with a special case. (-1).times() does the right thing, but 
there's no equivalent of "collect."  Any other options?  Maybe I should 
create my own range class?

- Martin

[prev in list] [next in list] [prev in thread] [next in thread] 

Configure | About | News | Add a list | Sponsored by KoreLogic