This scheme of expression evaluation is called substitution model.將一個表達式計算爲一個數值。對沒有side effects的表達式都可以使用。
Side effect:
Call-by-name
has the advantage that a function argument is not evaluated if the corresponding parameter is unused in the evaluation of the function body.
Call-by-value
has the advantage that it evaluates every function argument only once.
例:
def test(x:Int, y:Int) = x*x
test(3+4, 8)
Call-by-value
test(7,8)->7*7->49
Call-by-name
Test(7,8)->(3+4)*(3+4)->7*(3+4)->7*7->49
CBV evaluation of an expression e terminates, then CBN evaluation of e terminates, too. The other direction is not true.
Scala choose CBV. If you want to use the CBN, you can use the => to tell it like def constOne(x:Int, y:=>Int)=1
如果CBV能終止 那麼CBN一定能終止 反過來不成立
例子:
def first(x:Int , y:Int) =x
def loop()=loop
first(1,loop)
那麼CBN一定可以終止的 CBV不會,CBV會在loop造成循環。