3 ms·
> Lazy evaluation should be called a generator if we are doing JS specific naming conventions. The two are actually orthogonal -- generators are a control-flow
by cfallin 10y ago
> Lazy evaluation should be called a generator if we are doing JS specific naming conventions.
The two are actually orthogonal -- generators are a control-flow structure where control keeps re-entering an existing function context and returning from it (basically, a coroutine), whereas lazy evaluation is a language-semantics choice where every value starts out as a thunk (bit of code) with enough information to compute the value, until resolved to the result.
Generators in the Python or JavaScript sense aren't really doing "lazy evaluation" in the Haskell sense, IMHO, though I can see how one sees the parallels (infinite sequences, etc). You can have the same "infinite sequence" by just defining an iterator implementation that always returns a next value, without the use of generators/coroutines.
Likewise, there are other uses for lazy evaluation than generator-like infinite sequences. For example, lazy evaluation lets you build a (finite) table of values in a memoized dynamic-programming problem, where each value is an expression that refers to some of the other values, and the lazy evaluation semantics ensure that (i) only the needed values are computed and (ii) once a value is computed, it's memoized (the thunk resolves to its result). You get demand-based computation and memoization "for free" from the language runtime.