[Haskell-beginners] Understanding State

Jan Jakubuv jakubuv at gmail.com
Fri Jul 10 05:59:39 EDT 2009


Hi again,

sorry, now I see that it is not probably what you wanted because the first
monad parameter does not depend on `a`. So better try this version where the
first parameter is not a monad at all:

    update3 :: (a -> (r,a)) -> Int -> [a] -> State r [a]
    update3 f 0 (a:as) = let (r,a') = f a in put r >> return (a':as)
    update3 f i (a:as) = update3 f (i-1) as >>= return . (a:)

Sincerely,
    Jan.


On Fri, Jul 10, 2009 at 10:46:19AM +0100, Jan Jakubuv wrote:
> Hello Geoffrey,
> 
> when you really want to make the first function parameter (`a -> (r,a)`) a
> monad, you can use `r` as the state instead of `a` (and `[a]`). Then both
> the first parameter and the result are in the same monad `State r` and you
> can write:
> 
>     update2 :: State r a -> Int -> [a] -> State r [a]
>     update2 sm 0 (a:as) = sm >>= return . (:as)
>     update2 sm i (a:as) = update2 sm (i-1) as >>= return . (a:)
> 


-- 
Heriot-Watt University is a Scottish charity
registered under charity number SC000278.



More information about the Beginners mailing list