Jimm
Jimm

Reputation: 8515

call by name and value clarification

In Scala, does the following expression takes same number of steps, irrespective if you compute it by name or value?

The coursera scala lecture1.2 - Elements of Programming - says both should take the same # of steps, where as i am getting one extra step in Call by Name as shown below:

def test(x  : Int, y : Int)  = x *x

expression: test(2+3, 3*4)

Call By Value: (3 steps):

test(5, 12)

5*5

25

Call By Name: (4 steps):

(2+3) * (2+3)

5 * (2+3)

5 * 5

25

Upvotes: 0

Views: 59

Answers (1)

kiritsuku
kiritsuku

Reputation: 53358

Don't forget that in the call-by-value case the values need to be computed before the function is called:

// call-by-value
test(2+3, 3*4)
test(5, 3*4)
test(5, 12)
5*5
25

// call-by-name
test(2+3, 3*4)
(2+3)*(2+3)
5*(2+3)
5*5
25

Upvotes: 2

Related Questions