Haskell Lazy Evaluation and Reuse
Posted
by
Jonathan Sternberg
on Stack Overflow
See other posts from Stack Overflow
or by Jonathan Sternberg
Published on 2010-12-26T01:43:44Z
Indexed on
2010/12/26
1:54 UTC
Read the original article
Hit count: 544
I know that if I were to compute a list of squares in Haskell, I could do this:
squares = [ x ** 2 | x <- [1 ..] ]
Then when I call squares like this:
print $ take 4 squares
And it would print out [1.0, 4.0, 9.0, 16.0]. This gets evaluated as [ 1 ** 2, 2 ** 2, 3 ** 2, 4 ** 2 ]. Now since Haskell is functional and the result would be the same each time, if I were to call squares again somewhere else, would it re-evaluate the answers it's already computed? If I were to re-use squares after I had already called the previous line, would it re-calculate the first 4 values?
print $ take 5 squares
Would it evaluate [1.0, 4.0, 9.0, 16.0, 5 ** 2]?
© Stack Overflow or respective owner