By-value vs. by-name

A pure functional programming language typically uses a by-need evaluation strategy for the arguments of function calls. Scala is a multi-paradigm programming language that also supports the imperative, in an object-oriented way, paradigm. This rules-out by-need, but would let think that the by-name approach would be followed. Still, reasons of efficiency pushed Martin Odersky to chose a by-value approach by default, and leaving the by-name as an alternative.

A trivial example should help clarify the difference about the two approaches.

Let's consider a useless function that gets as parameters a couple of integers and always returns zero.
def zero(a: Int, b: => Int) = 0
Notice that the first parameter is passed to the function by-value, while the second, as specified by the arrow "=>" notation, is passed by-name.

Function zero() looks pretty harmless. However, we could have big troubles if we use it in conjunction with something like this:
def silly() : Int = silly
Function silly() just resolves in an infinitive loop, that would let our program running forever without giving the user any satisfaction.

If I pass silly() to zero() as its second parameter, I'll have no problem at all:
println(zero(42, silly))
Being passed by-name, and not being actually used in zero(), silly() won't be evaluated.

On the contrary, you want to avoid this:
println(zero(silly, 42)) // !!!
Here silly() is passed by-value, this means that Scala tries to calculate its value to pass it to zero(), even if it has no use at all for it. And this would let the user waiting forever for its feedback.

No comments:

Post a Comment