[Haskell-cafe] Lazy Evaluation in Monads

Gregory Crosswhite gcross at phys.washington.edu
Tue May 31 22:54:54 CEST 2011


On 5/31/11 12:49 PM, Scott Lawrence wrote:
> I was under the impression that operations performed in monads (in this
> case, the IO monad) were lazy.

Whether they are lazy or not depends entirely on the definition of the 
monad.  For example, if you look up the ST and State monads you will 
find that they come in strict and lazy flavors.

As a general rule, operations in the IO monad are strict except for very 
special cases which are explicitly labeled as such, e.g. 
unsafeInterleaveIO, lazyIO, etc.

FYI, in GHC the definition of IO is at

     
http://www.haskell.org/ghc/docs/7.0.3/html/libraries/ghc-prim-0.2.0.0/src/GHC-Types.html#IO

You can tell it is strict because the result of the map is an unboxed 
tuple, which is strict (at least, if I understand correctly :-) ).

If you are curious, State# and RealWorld are defined here:

     
http://www.haskell.org/ghc/docs/7.0.3/html/libraries/ghc-prim-0.2.0.0/src/GHC-Prim.html#State.

State# and RealWorld do not contain data constructors because they are 
not intended to contain data but rather to parametrize types --- that is 
to say, you can think of IO as being a special case of the strict ST 
transformer which uses a special type tag to keep different ST threads 
separate (even though this type is never instantiated), and in the case 
of IO the state tag is RealWorld.

So in short, monads need not be strict but often are, and in particular 
IO is designed to be strict because it is essentially just a special 
case of the strict ST monad.

Cheers,
Greg



More information about the Haskell-Cafe mailing list