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 strict.

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")
or
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.

_______________________________________________
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe

Reply via email to