[Haskell-cafe] Shouldnt this be lazy too?

Jules Bean jules at jellybean.co.uk
Tue Sep 25 10:32:46 EDT 2007


Vimal wrote:
>>From the wiki:
>> If you write it, you force Haskell to create all list nodes. ...
> 
> Alright.
> Now, lets look at the definition again:
> 
>> length [] = 0
>> length (x:xs) = 1 + length xs
> 
> We see that the value of *x* isnt needed at all. So, why does GHC
> allocate so much memory creating all those *x*s? because, if we have:
> 
> length [1..] = 1 + length [2...] = 1 + 1 + length [3...]
> 
> This should go on, into an infinite loop. GHC doesnt need to create
> all nodes! The wiki also claims that *x* isnt evaluated. So, why
> allocate space for it when its not evaluated?


*x* isn't allocated.

What is allocated is the list cell, that is, the ":".

The ":" is conceptually a two-cell, with room for a pointer to the 'x' 
and a pointer to the 'xs'.

The 'x' itself isn't evaluated, so that pointer remains as a pointer to 
some code a.k.a. an unevaluated thunk.

Jules


More information about the Haskell-Cafe mailing list