Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XTend For-Loop Support and Adding Range Support

I can't seem to find a great way to express the following in Xtend without resorting to a while loop:

for(int i = 0; i < 3; i++){
    println("row ");
}
println("your boat");

So, I guess my question has two parts:

  • Is there a better way to do the above? I didn't see anything promising in their documenation
  • A large portion of the features the language has are just Xtend library extensions (and they're great!). Is there range() functionality à la Python that I don't know about?

I ended up rolling my own and got something like the following:

class LanguageUtil {

def static Iterable<Integer> range(int stop) {
    range(0, stop)
}

def static Iterable<Integer> range(int start, int stop) {
    new RangeIterable(start, stop, 1)
}

def static Iterable<Integer> range(int start, int stop, int step) {
    new RangeIterable(start, stop, step)
}
}

// implements Iterator and Iterable which is bad form.
class RangeIterable implements Iterator<Integer>, Iterable<Integer> {
val int start
val int stop
val int step
var int current

new(int start, int stop, int step) {
    this.start = start;
    this.stop = stop;
    this.step = step
    this.current = start
}

override hasNext() {
    current < stop
}

override next() {
    val ret = current
    current = current + step
    ret
}

override remove() {
    throw new UnsupportedOperationException("Auto-generated function stub")
}

/**
 * This is bad form. We could return a 
 * new RangeIterable here, but that seems worse.
 */
override iterator() {
    this
}
}
like image 951
Bface Avatar asked Aug 26 '12 01:08

Bface


1 Answers

The exact replacement for

for(int i = 0; i < 3; i++){
    println("row ");
}

is

for (i : 0 ..< 3) {
    println("row ")
}

Notice the exclusive range operator: ..<

like image 84
rzymek Avatar answered Feb 05 '23 02:02

rzymek