Understanding strictness of ghc output

Malcolm Wallace Malcolm.Wallace at cs.york.ac.uk
Tue Jun 22 08:52:44 EDT 2004


Adrian Hey <ahey at iee.org> writes:

> height :: AVL e -> Int
> height = addHeight 0 where
>  addHeight h  E        = h
>  addHeight h (N l _ _) = addHeight h+2 l 
>  addHeight h (Z l _ _) = addHeight h+1 l  
>  addHeight h (P _ _ r) = addHeight h+2 r 
> 
> It seems pretty obvious to me that addHeight is strict in its
> first argument if + is strict for Ints (as I guess it is).

No, this looks very obviously lazy to me.  The first argument is always
a pattern variable, h, and therefore no evaluation is required on it -
the value is just bound lazily and used on the RHS.

> height :: AVL e -> Int
> height = addHeight 0 where
>  addHeight h  E        = h
>  addHeight h (N l _ _) = let h' = h+2 in h' `seq` addHeight h' l 
>  addHeight h (Z l _ _) = let h' = h+1 in h' `seq` addHeight h' l  
>  addHeight h (P _ _ r) = let h' = h+2 in h' `seq` addHeight h' r 
> 
> .. it still gives "DmdType LS".

Even though many uses of 'h' are strictified, the first clause
   addHeight h  E        = h
is still lazy, because it simply binds the variable without forcing it.

> height :: AVL e -> Int
> height = addHeight 0 where
>  addHeight h  E        = h
>  addHeight h (N l _ _) = h `seq` addHeight (h+2) l 
>  addHeight h (Z l _ _) = h `seq` addHeight (h+1) l  
>  addHeight h (P _ _ r) = h `seq` addHeight (h+2) r

Same again.  Try
   addHeight h  E        = h `seq` h

which, although it looks bizarre, actually forces the evaluation of h,
whilst simply returning it does not.

Regards,
    Malcolm


More information about the Glasgow-haskell-users mailing list