[Haskell-cafe] Re: sort and lazyness (?)

Bayley, Alistair Alistair.Bayley at invesco.com
Fri Dec 19 10:54:44 EST 2008

> 	> How does reverse work in constant space?  At the 
> moment I can't imagine
> 	> it doing so; that's why I tried it, but of course you 
> could be right.
> 	It allocates a new list cell for every cell it finds in 
> the input list.
> 	If the input list can be garbage collected then reverse 
> takes constant
> 	space because each time it inspects a list cell from 
> the input list that
> 	cell can be garbage collected. If the input list is 
> being retained for
> 	some other reason then reverse will take linear space.
> I don't think that's true.  It must inspect the whole input 
> list to give the first element of the output list, but it 
> cannot garbage collect the input list because it needs to 
> yield every element of it.

reverse creates the output list by pulling items from the head of the
input list, and prefixing them to the output list. After each item has
been pulled from the input, the list node can be GC'd from the input
list. Also, if the output list is itself being consumed by a function
which does not require the entire list (like length) then again the list
node can be GC'd soon after consumption.

> ghci>  length $ reverse [1..10^7] 

This is a compiler optimisation, I think, so will probably require ghc

Confidentiality Note: The information contained in this message,
and any attachments, may contain confidential and/or privileged
material. It is intended solely for the person(s) or entity to
which it is addressed. Any review, retransmission, dissemination,
or taking of any action in reliance upon this information by
persons or entities other than the intended recipient(s) is
prohibited. If you received this in error, please contact the
sender and delete the material from any computer.

More information about the Haskell-Cafe mailing list