0

I am studying for a final, and I have a practice problem here.

The question asks for the result of

val y = ref 1;
fun f x = (!y) + (x + x);
(f (y := (!y)+1; !y)) + (!y);

under the following parameter passing techniques:

  1. Call by value
  2. Call by name
  3. Call by need.

It seems to me that for call by value, the answer is 8. However, I believe the answer for call by name is also 8, but I would expect it to be different. The reason I think it is 8:

  • y := (!y)+1 derefs y as 1, adds 1, and then sets y to 2
  • !y in line 3 serves as the argument to f, and since it is being dereferenced it is passed as a value rather than as a reference (this may be where I am going wrong?)
  • The function call returns 6, but does not set y as y was passed in as a value from the previous step
  • 6 is added to the dereferenced value of y, which is 2.
  • This returns 8

Is this the correct answer, and if not, can someone please point out where I have gone wrong? Also, can someone explain to me how call by need would work in this situation also?

Many thanks.

Davido Widre
  • 185
  • 2
  • 13
  • It looks like you are explaining how it would proceed with call-by-value. How did you arrive at your answer for call-by-name? – Scott Hunter Dec 07 '14 at 23:33
  • The process I explained was my understanding of how it should work with call-by-name. I think it is wrong, because as you said it seems exactly the same as call-by-value, but I do not know how it is wrong. – Davido Widre Dec 07 '14 at 23:53

1 Answers1

1

I found out how it works:

(y := (!y)+1; !y) is the parameter passed to f. f then looks like:

fun f x = (!y) + ((y:= (!y)+1; !y) + (y:= (!y)+1; !y));

so this ends up being 1+2+3, and the final step + (!y) adds 3 as this is the current value of y, giving 9.

Thanks for pointing out that I was still doing call-by-value.

Davido Widre
  • 185
  • 2
  • 13