Yet Another Monad Tutorial

Wolfgang Jeltsch wolfgang@jeltsch.net
Tue, 12 Aug 2003 13:37:33 +0200


On Tuesday, 2003-08-12, 13:10, Alistair Bayley wrote:
> > From: Wolfgang Jeltsch [mailto:wolfgang@jeltsch.net]
> >
> > For example, the function readFile is pure. For a specific string s the
> > expression readFile s always yields the same result: an I/O action which
> > searches for a file named s, reads its content and takes this content as
> > the result of the *action* (not the expression).
>
> What about getChar? This is a function which takes no arguments, yet returns
> a (potentially) different value each time. I know, I know: it returns an IO
> action which reads a single char from the terminal and returns it.

Actually, getChar is not a function at all but it *is* the action you 
describe. ;-)

> Is the IO monad the only one (currently) in which you would say that it
> "returns an action", which is then executed by the runtime system? I would
> have thought that monads that are not involved in IO (e.g. State) would be
> pure in the sense that Van Roy was thinking. You wouldn't need to describe
> functions in them as "returning an action".

State is similar to I/O. For example, take the function
    gets :: (state -> val) -> State state val.
gets doesn't return a value of type val the same way readFile doesn't return a 
string. Instead, gets returns some kind of "state-transforming action" of 
type State state val which is internally represented by a function.

The difference to the IO type is that you can implement useful (pure) 
functions with a type like
    ... -> State state val -> ... -> result
where result doesn't involve the State type. So you can "execute" a state 
transformer as part of an expression evaluation and without special support 
by the runtime system. State is pure in the sense that pure "execution" is 
possible.

Wolfgang