[Haskell-cafe] small example for space-efficiency via lazy evaluation?
Albert Y. C. Lai
trebla at vex.net
Wed Sep 5 20:09:49 UTC 2018
On 2018-09-04 12:36 PM, Johannes Waldmann wrote:
> main = print $ sum $ map (^ 2) $ [ 1 :: Int .. 10^8 ]
> So, my question is, what do you use as a (teaching) example
> for space-efficiency via lazy evaluation?
I would skip the summing. Print the whole list.
Sure it would take forever to finish, but during that time I would also
fire up htop or something to show how much memory the process doesn't
use as it progresses.
And change Int to Integer and bump up the upper bound to 10^12 or
something --- or even have no upper bound at all. And point out how the
printing starts right away as opposed to "waiting for the whole list to
be completely built before printing begins".
And for the sake of engagement, before running the experiment, invite
the students to make predictions about how much memory, how it grows,
how much time before the printing begins, etc. Learning does not happen
by nodding. Learn happens by dropping your jaw all the time.
In my class I used these two other examples (because I didn't want to do
doITerminate = take 2 (foo 0)
foo n = n : foo (n + 1)
doIEvenMakeSense = take 2 foo
foo = 0 : foo
They're merely "take 2" because next I also had to showed the detailed
steps of lazy evaluation. It would be boring to go "take 10".
More information about the Haskell-Cafe