by luismarques · 10y ago · 0 comments
edit: (also, D's lazy keyword, which performs the transformation described in the article automatically)
numbers = [0,1,2,3,4,5,6,7,8,9]
take 5 numbers
-- [0,1,2,3,4]
numbers = [0..]
take 5 numbers
-- [0,1,2,3,4]
evenNumbers = map (* 2) numbers
take 5 evenNumbers
-- [0,2,4,6,8]
last evenNumbers
-- <<infinite loop>>
I used simple list stuff in this illustration, but everything is lazy. I/O most notably (and sometimes problematically). Nothing runs until it's forced[0], and none of this requires any special annotation or plumbing.----
[0] Yes, I know. But it's subtle, and we're in public here. https://wiki.haskell.org/Lazy_vs._non-strict
In larger Haskell programs, I've found that the most challenging issue to debug: "why does my program use way too much memory?".
So, don't create a list of numbers if you intend to sum it, use a non- lazy data structure.
The trick is that Haskell's common default structures are lazy.