[Haskell-cafe] Lazy Evaluation in Monads
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
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:
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.
More information about the Haskell-Cafe