[Haskell-beginners] [Haskell-cafe] select :: [(Float, a)] -> a -- Weighted stochastic selection - help?

apfelmus apfelmus at quantentunnel.de
Mon Sep 8 02:28:46 EDT 2008

Tony Hannan wrote:
> The IO monad is defined as:
> newtype IO a = IO (RealWorld -> (RealWorld, a))
> Notice that it encapsulates a pure function from RealWorld to RealWord plus
> result. Semantically, the whole state of the world is passed into your main
> function and a new world state is returned containing any changes you made.
> However, the implementation just performs side effects on the world (I/O),
> but the monad type ensures that these side effects are sequential and that
> you can never gain access to the underlying RealWorld so it won't be
> duplicated. These restrictions allow us to view this implementation as a
> pure function.

Note that while

  IO a  ~  RealWorld -> (RealWorld, a)

is an intuitive way to think about IO, it's not the definition of IO and it
doesn't always work. For instance, it's inadequate for modeling concurrency. But
also in a sequential world, there are problems: consider the two programs

  loop, loop' :: IO ()
  loop  = loop
  loop' = putStr "X" >> loop'

Both would have the denotation _|_ while being very different: one does nothing
at all while the other prints an infinite stream of Xs.

For more on the semantics of IO, see also

  Simon Peyton Jones. Tackling the Awkward Squad.

> Non-primitive monads like Control.Monad.State are actually implemented as
> pure functions passing the state around.

Yes, so the difference between IO and the other monads is of course that IO is a
primitive and cannot be implemented with other Haskell constructs.


More information about the Beginners mailing list