[Haskell-beginners] Disappointing thought on Haskell -- a simple space leak on "insert" is hard bug to catch

Heinrich Apfelmus apfelmus at quantentunnel.de
Wed Aug 20 13:41:32 UTC 2014


KC wrote:
> Heinrich Apfelmus wrote:
>> 
>> "But in the expression,
>> 
>>    let x = "A String which uses a lot of memory"
>>        y = 12
>>    in snd (x,y+2)
>> 
>> we may not discard `x` just yet, because it still occurs in the expression
>> `snd (x,y+2)`. Of course, performing reduction step will turn this into
>> `y+2` and now the memory used by binding for `x` can be freed."
>> 
>
> Wouldn't the compiler know how "snd" works and therefore know that the
> first argument isn't needed?
> 
> Isn't the above the advantage of pure code - same inputs ~ same outputs?

What does it mean for a compiler to know something?

Evaluation of a Haskell program follows a deterministic process. In the 
case of lazy evaluation, it is: Repeatedly find the outermost leftmost 
redex and reduce it, occasionally do a garbage collection to remove 
unused bindings (graphs). That's all there is to it. In this context, 
the example I gave above retains the binding `x` slightly longer than 
strictly necessary from a semantic point of view.

Of course, before executing a Haskell program, the compiler can try to 
analyze it and find transformations that may make its subsequent 
execution more efficient. For instance, the fact that `snd` does not 
depend on the first component of the pair can be caught by strictness 
analysis, and the compiler might choose to inline it. However, once the 
compiler is done with the optimization phase, it will produce a program 
that follows the lazy evaluation strategy to its bitter -- or joyous -- 
end, space leaks and all.


Best regards,
Heinrich Apfelmus

--
http://apfelmus.nfshost.com




More information about the Beginners mailing list