[Haskell-cafe] State Monad

Tom Pledger tpledger at ihug.co.nz
Thu Mar 4 08:51:04 EST 2004


Georg Martius wrote:
[...]

> I could write:
>
> modifyT :: ((a, String) -> (a, String)) -> a ->  State String a
> modifyT trans a = do str <- get
>               let (a', str') = trans (a, str)
>              put str'
>               return a'
>
> f :: State String ()
> f = do put "hallo"
>      modify strTrans
>      i <- modifyT strIntTrans 4    -- strIntTrans :: (Int, String) -> 
> (Int, String)
>      i' <- modifyT strIntTrans i   
>      ...
>
> But this is obviously awkward.

[...]

Hi.

People have already replied about the state monad aspect, but there's 
another small improvement I'd like to suggest.

Look at what modifyT does with 'trans' and 'a'. They are always used 
together. So, how about combining them *outside* the definition of modifyT?

    modifyT :: (String -> (a, String)) -> State String a
    modifyT trans = do (a, s) <- gets trans
                       put s
                       return a
    f = do ...
           i  <- modifyT (strIntTrans 4)  -- strIntTrans :: Int -> 
String -> (Int, String)
           i' <- modifyT (strIntTrans i)
           ...

Aside: if you rewrite ($) similarly, you get id.

Regards,
Tom




More information about the Haskell-Cafe mailing list