[Haskell-cafe] Re: How to make code least strict?

ChrisK haskell at list.mightyreason.com
Mon Jan 19 12:10:34 EST 2009

Robin Green wrote:
> What guidelines should one follow to make Haskell code least-strict?

Obviously the use of "seq" and bang-patterns make code more strict.

Code is strict when it evaluates values to determine a pattern match.  So 
avoiding that makes code lazier.  Values are evaluated when decisions have to be 
make in order to choose what an expression will evaluate to.  Avoiding "case" 
statements and things that de-sugar to case statements such as "if then else" 
and pattern matching.  Put off examining the input values.  Occasionally the use 
of "lazy" patterns, preceded by ~, can help make code both more compact and less 

Consider that the order of pattern matching can matter as well, the simplest 
common case being zip:

zip xs [] = []
zip [] ys = []
zip (x:xs) (y:ys) = (x,y) : zip xs ys

The order of the first two lines of zip's definition affects whether
zip [] (error "boom")
zip (error "bam") []
will be an error.  This shows that "least-strict" is not a unique goal.

For the choice I just made the "zip [] (error "boom")" will cause an error 
because the first definition line of zip checks the second argument, while "zip 
(error "bam") []" will evaluate to [].

The other way to reduce strictness is to be more polymorphic because this 
reduces what can be sensibly done with the arguments.

More information about the Haskell-Cafe mailing list