Call-by-name evaluation and foreach loop

83 Views Asked by At

I faced this problem for the first time and I can't figure it out.

Let's say we have an array and a foreach loop. Something like this:

var v = array(10,20,50);
var i = 0
write(foo(v, v[i++]));

function foo(ref int[] v, name int y){
  foreach(int j in v){
    write(y);
  }
  return y;
}

Am I wrong or something is not gonna work here? I mean, every time I will loop thru the foreach I will evaluate the y (by name) so, being v[i++] I will increase the value of my i variable by one.

  1. So first step y = v[0] so write(10) then i++ (i=1).
  2. Second step y = v[1] so write(20) then I increase i by one (i=2).
  3. Third and last step y = v[2] so write(50) and i++ again, which now equals to 3.

Now, what value should it return?! If I evaluate again y, I can't do y = v[3] cause I go out of bounds. Am I doing anything wrong? Should I just evaluate y once, before the foreach loop? There must be something with the foreach I'm not taking in account when calling parameters by name.

Dunno, I'm a bit confused.

Thanks in advance!

0

There are 0 best solutions below