[Haskell-beginners] Transforming (State s a) to (StateT s m a)

Toby Murray toby.murray at comlab.ox.ac.uk
Tue Aug 4 07:36:07 EDT 2009


Hi all,

Am very new to Haskell, apologies in advance.

Suppose I have a transformer A of type State s a.

Suppose I have other state transformers of type StateT s m a. These
are similar to the first kind but e.g. might throw errors or perform
IO or whatever.

I can manually convert A to be of the second kind as follows:

-- | Used to invoke a "pure" state transformer
--   from a context in which other effects may occur.
pure :: (Monad m) => State s a -> StateT s m a
pure func = StateT (\arg -> (return (runState func arg)))

This seems like something one might want to do often. For instance, I
might have a state type that I want to operate on, call it System.
Then

type PureSystemTransformer a = State System a

defines a type for "pure" System transformers that return results of type a.

However, other system transformers might need to throw errors. So I might define

type SystemTransformer a e = StateT System (Either e) a

for the type of system transformers that return results of type a or
throw errors of type e.

'pure' is then used to convert a PureSystemTransformer to a SystemTransformer.

I wonder whether there is something in the standard libraries that
achieves the same thing as 'pure' above.
i.e. Is there a more standard way to do this?

Cheers

Toby


More information about the Beginners mailing list