When is it better to use lazy evaluation instead of the eager one? Is it better when you know that the expression will be computed only once or maybe never?

有帮助吗?

解决方案

If you have the choice, use lazy evaluation for expressions that may not be evaluated at all or may lead to programming errors under certain circumstances when evaluated.

The classic case is implemented in most languages descending from C and is called "short circuit operators":

if (i != 0 && n/i > 100) ...

Here, n/i > 100 will only be computed when i is not 0. Which is nice, since it avoids a zero divide error.

其他提示

Why Functional Programming Matters is the quintessential argument in favor of lazy evaluation, mainly as a facilitator of improved modularity.

I can offer you as an example a lazy formulation for primes by sieve of Eratosthenes,

primes = (cons 2 . diff [3..] . bigU . map (\p-> [p*p, p*p+p..])) primes

(.) is function composition, diff is a set difference, bigU finds union of (ordered) list of (ordered, increasing) lists of numbers, map is map, etc...., which without the lazy semantics would have to maintain all kinds of mechanics explicitly, mashed together, instead of using these nice separate modular functions chained together with a function composition.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top