[Haskell-cafe] one-way monads

Ben Lippmeier Ben.Lippmeier at anu.edu.au
Tue May 20 03:19:07 EDT 2008


On 20/05/2008, at 3:54 PM, Zsolt SZALAI wrote:

> Here comes IO and one-way monads, where the internal state can not be
> extacted, and seems, that the internal data is global to the program.
> Hows that could be? Is it just because main::IO() or because the
> implementation of IO uses external C functions and there are no
> internal state in the monad itself at all?

Operationally, the IO monad doesn't have any internal state. The  
'state' would be the outside world - which can't really be represented  
at runtime.

The IO monad is a state monad that passes around a special token that / 
represents/ the outside world. What the token actually is doesn't  
matter, but passing it around in a single threaded manner in the Core  
IR provides data dependencies that ensure that operations on the world  
happen in the correct order. References to this token actually get  
erased before code generation. In GHC this erasure is called the  
'state-hack'.

> And why one can not write a function that makes an IO computation and
> the return type does not include and IO contructor? It is a feature of
> the language and specific to IO, or anybody  could write a monad with
> this property(one-way), assuming the implementation does not use
> external languages?

IO isn't a feature of the language, it's a type defined in the  
library. You can define your own IO-style monads if you like.

> Or the one-way property is just that, there is no such functions, that
> allow extracting internal data?

Just that. It's one way because there are no functions convert an 'IO  
a' into an 'a' (mostly). Doing that would break the desired single- 
threadedness property.

If you're convinced that violating this single-threadedness won't  
break your program you can use unsafePerformIO :: IO a -> a, but this  
performs the action, it doesn't give you the actual world token.

Ben.




More information about the Haskell-Cafe mailing list