3

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
    Ah I see it now: Array.ofSize doesn't take a callback, and even if it did, I shouldn't execute the callback as I pass it as argument to Array.ofSize –  Sep 08 '17 at 09:32
  • I want to close this question, but apparently I'm not sufficiently powerful –  Sep 08 '17 at 09:34
  • 3
    By the way there's no need to init a new Integer in `return Integer(myInteger);` because Integers are immutable. Just `return myInteger` will do. – Tom Bentley Sep 08 '17 at 11:42

2 Answers2

4

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.

Gavin King
  • 3,182
  • 1
  • 13
  • 11
3

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.

Paŭlo Ebermann
  • 73,284
  • 20
  • 146
  • 210