Call by value, name/reference, need in ML

845 views Asked by At

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.

1

There are 1 answers

0
Davido Widre On

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.