[Haskell-beginners] Understanding how laziness works
matt at dancingfrog.co.uk
Tue Jun 19 18:20:15 CEST 2012
Apologies for the maybe double post (no subject and hadn't confirmed
the mailing list first time I sent this).
Here's a simple expression
double ( double [1,2,3,4] ) !! 0
The 1st element of a list is
double ( 1*2 : double [2,3,4] ) !! 0
1*2*2 : double ( double [2,3,4 ] ) !! 0
calculated without having to traverse the rest of the list due to laziness.
But how far does the laziness extend? For example, if I take the 2nd element
double (double [1,2,3,4]) !! 1
Do we have
1*2*2 : double ( 2*2 : double [3,4] ) !! 1
1*2*2 : 2*2*2 : double ( double [3,4] ) !! 1
Resulting in 8.
I assume that the 1st list entry 1*2*2 doesn't actually get
calculated, but the expression does get formed? The second element
(index 1) gets formed, isolated (by !!) and calculated as the return
value. And then
things can happily stop.
What I'm checking is that the laziness doesn't some how magically
extend to not having to form the preceding expressions that make up
the resulting list? Or can Haskell recognize that this is like doing
function composition i.e.,
(double . double) [ 1 2, 3, 4 ] !! 1
Thanks for any answer.
p.s, I kinda hope things are how I've assumed as the example finally
shows me some concrete benefit of function composition which has
never seemed important given it's so easily re-written as application.
More information about the Beginners