Incrementing integers

77 views Asked by At

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?

2

There are 2 answers

0
Gavin King On BEST ANSWER

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.

0
Paŭlo Ebermann On

You already found what is happening here ... the constructor Array.ofSize(n, val) is creating an array filled with n times the same value.

A way of doing what you want might be this:

Array<Integer> integers =
        Array({ getInteger() }.repeat(4));

(Try it.)

The expression in the iterable enumeration (this is the { getInteger() } here) is evaluated lazily each time the iterator's next method is invoked (which is happening 4 times here, due to repeating the iterable 4 times).

Note that it won't work if you use a sequence enumeration [ ... ] instead, those are non-lazy.