开发者

Difference between Call-By-Name and Call-By-Reference

Parameter passin开发者_如何学Gog techniques:

From what I can gather on these two techniques.

Call By Reference:

The address location of the variable is being passed into the function, thus within the local scope of the function, any changes to the value of the local variable will change the value of the original variable, since they are pointing to the same place.

Call By Name:

The actual variable is being passed into the function. Any changes to the value of the variable inside the local scope of the function will also be reflected on the outside of the function.

It seems to me, these two parameter passing techniques accomplish the same thing? Both of them act on the original variables contents. Do I have my definitions wrong? Am I thinking about this in the wrong way?


Call-by-name is slightly different than you describe. In pseudo code, imagine:

function foo(index, value-increment)
    sum = 0
    loop index = 1 to 3
        sum = sum + value-increment
    return sum

x = 3
foo(x, 1 / x)

If our foo call is by reference, the second argument, 1 / x, is evaluated only once giving us effectively: 1/3 + 1/3 + 1/3. It is a strict evaluation - each argument is fully evaluated before the function is applied.

If we call by name, 1 / x is not strictly evaluated. Instead, it's evaluated in the loop as it's needed. Effectively, the loop becomes:

loop x = 1 to 3
    sum = sum + 1 / x

or 1/1 + 1/2 + 1/3.

Take a look at thunks, though thunks don't always mean call-by-name. Haskell has the idea of thunks but uses call-by-need where 1 / x wouldn't be evaluated until it was needed but then would be evaluated only once (not to mention Haskell wouldn't have a mutable loop variable).

Other resources:

  • Call-by-name on the C2 wiki
  • Pass-by-name in CMPT 383 at Simon Fraser U.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜