What is “pass-by-name” and how does it work exactl

2019-01-13 14:55发布

I've check wikipedia, and googled but I still can't wrap my mind around how pass-by-name works in ALGOL 60.

8条回答
Evening l夕情丶
2楼-- · 2019-01-13 15:58

I found a good explanation at Pass-By-Name Parameter Passing. Essentially, the body of a function is interpreted at call time after textually substituting the actual parameters into the function body. In this sense the evaluation method is similar to that of C preprocessor macros.

By substituting the actual parameters into the function body, the function body can both read and write the given parameters. In this sense the evaluation method is similar to pass-by-reference. The difference is that since with pass-by-name the parameter is evaluated inside the function, a parameter such as a[i] depends on the current value of i inside the function, rather than referring to the value at a[i] before the function was called.

The page I linked above has some more examples of where pass-by-name is both useful, and dangerous. The techniques made possible by the pass-by-name are largely superseded today by other, safer techniques such as pass-by-reference and lambda functions.

查看更多
做个烂人
3楼-- · 2019-01-13 15:59

Flatlander has an illuminating example of how it works in Scala here. Suppose you wanted to implement while:

def mywhile(condition: => Boolean)(body: => Unit): Unit =
  if (condition) {
    body
    mywhile(condition)(body)
  }

We can call this as follows:

var i = 0
mywhile (i < 10) {
  println(i)
  i += 1
}

Scala is not Algol 60, but maybe it sheds some light.

查看更多
登录 后发表回答