On Mon, 2007-12-03 at 10:48 +0100, Ketil Malde wrote:
> "Johan Tibell" <[EMAIL PROTECTED]> writes:
> 
> > It would be great if someone could exemplify these "rules of thumb",
> > e.g. "Primitive types such as Int should be strict unless in the three
> > canonical examples X, Y and Z." My strictness radar is still quite
> > poor and I feel I can't make informed decisions on when I need to make
> > something more strict or lazy.
> 
> I find that I often need to add strictness when:
> 
>  left thumb)  parsing [Char] into something more compact, i.e. almost
>               all cases.
>  right thumb) storing data into maps, especially when the values are produced 
> by
>               multiple updates - i.e. doing word frequency counts.

Indeed, this generalizes fairly well.  In general when going from a
"large" structure (especially recursive types or arrays) to a "small"
one (especially base types or small non-recursive types e.g. a vector
type) you want strictness.  Cale Gibbard argues that this is the only
case where strictness is desirable.  In the other three cases, "small"
to "large", "large" to "large" and "small" to "small" either laziness is
preferable or there is not a big difference between them.

http://www.haskell.org/haskellwiki/Stack_overflow gives some advice on
how to choose strictness for avoiding stack overflows.  On that page you
can see the above rule in action in, for example, the difference between
concat :: [[a]] -> [a] and sum :: Num a => [a] -> a.

The techniques sidebar on the Performance page,
http://www.haskell.org/haskellwiki/Performance also contains some bits
of advice.  For example, the widely known advice about making
accumulating parameters strict.  This is related to Ketil's "right rule
of thumb."

Oftentimes the best way to get good behaviour is to use strict (in the
appropriate places) data constructors.  This will often eliminate most
or all of the need for (other) strictness annotations.  For example, one
way of solving the issue with the scanl code on the Stack Overflow wiki
page is by using a head strict list type (which, incidentally, Clean has
native support for.)  In fact, I suspect most of the time a head strict
list type is either comparable or what is desired (though certainly not
all of the time).

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

Reply via email to