Search code examples
ceylon

Incrementing integers


I'm having some trouble incrementing a variable integer. This code:

variable Integer myInteger = -1;
Integer getInteger () {
    myInteger = myInteger + 1;
    print("myInteger: " + myInteger.string);
    return Integer(myInteger);
}

Array<Integer> integers =
        Array.ofSize(
            4,
            getInteger());

print(integers);

Gives this output:

myInteger: 0
{ 0, 0, 0, 0 }

while the intended output was:

myInteger: 0
myInteger: 1
myInteger: 2
myInteger: 3
{ 0, 1, 2, 3 }

What's up with that?


Solution

  • Your example, which I assume is contrived, can be written as Array(0:4) or Array(0..3). But assuming that you have some good reason to want to loop over a generating function, here is how I would write it:

    Array(loop(0)((i) => i+1).take(4))
    

    Or, equivalently:

    Array(loop(0)(Integer.successor).take(4))
    

    Or even:

    Array(loop(0)(1.plus).take(4))
    

    That's much better, IMO, than using a stream which accesses a variable in an outer scope.