[Haskell-beginners] Question about lazy evaluation
Zhi-Qiang Lei
zhiqiang.lei at gmail.com
Thu Sep 8 07:56:14 CEST 2011
Hi,
I am confused about this piece of explanation in Real World Haskell.
-- file: ch08/append.hs
(++) :: [a] -> [a] -> [a]
(x:xs) ++ ys = x : (xs ++ ys)
[] ++ ys = ys
In a strict language, if we evaluate "foo" ++ "bar", the entire list is constructed, then returned. Non-strict evaluation defers much of the work until it is needed.
If we demand an element of the expression "foo" ++ "bar", the first pattern of the function's definition matches, and we return the expression x : (xs ++ ys). Because the (:) constructor is non-strict, the evaluation of xs ++ ys can be deferred: we generate more elements of the result at whatever rate they are demanded. When we generate more of the result, we will no longer be using x, so the garbage collector can reclaim it. Since we generate elements of the result on demand, and do not hold onto parts that we are done with, the compiler can evaluate our code in constant space.
When ('f' : "oo") ++ "bar" becomes 'f' : ("oo" ++ "bar") and then becomes 'f' : ('o' : ("o" ++ "bar")), we still need 'f', don't we?
Best regards,
Zhi-Qiang Lei
zhiqiang.lei at gmail.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/beginners/attachments/20110908/25cfece1/attachment-0001.htm>
More information about the Beginners
mailing list