This is just one of those “I was wondering…” questions.
Scala has immutable data structures and (optional) lazy vals etc.
How close can a Scala program be to one that is fully pure (in a functional programming sense) and fully lazy (or as Ingo points out, can it be sufficiently non-strict)? What values are unavoidably mutable and what evaluation unavoidably greedy?
Regarding lazyness – currently, passing a parameter to a method is by default strict:
but you use call-by-name parameters:
but this is not lazy in the sense that it computes the value only once when needed:
There’s been some work into adding lazy method parameters, but it hasn’t been integrated yet (the below declaration should print
"calculating"from above only once):This is one piece that is missing, although you could simulate it with a local lazy val:
Regarding mutability – there is nothing holding you back from writing immutable data structures and avoid mutation. You can do this in Java or C as well. In fact, some immutable data structures rely on the lazy primitive to achieve better complexity bounds, but the lazy primitive can be simulated in other languages as well – at the cost of extra syntax and boilerplate.
You can always write immutable data structures, lazy computations and fully pure programs in Scala. The problem is that the Scala programming model allows writing non pure programs as well, so the type checker can’t always infer some properties of the program (such as purity) which it could infer given that the programming model was more restrictive.
For example, in a language with pure expressions the
a * ain the call-by-name definition above (a: =>Int) could be optimized to evaluateaonly once, regardless of the call-by-name semantics. If the language allows side-effects, then such an optimization is not always applicable.