[Haskell-beginners] Understanding State

Jan Jakubuv jakubuv at gmail.com
Fri Jul 10 05:46:19 EDT 2009


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:)

Nevertheless in both cases (update' and update2) you need to pass some bogus
initial state (or a value in the case of update') to run the computation. In
this case I would use the `Writer r` monad anyway.

Finally just note that `State a` and `State [a]` are different monads and
they can not be easily used in the same computation (although it's indeed
possible).

Sincerely, 
  Jan.


On Thu, Jul 09, 2009 at 10:34:29PM -0600, Geoffrey Marchant wrote:
> 
> Which leads to me writing this:
> 
> > update' s 0 = do
> >    (a:as) <- get
> >    let (r, a') = runState s a
> >    put (a':as)
> >    return r
> > update' s i = do
> >    (a:as) <- get
> >    put as
> >    r <- update' s (i-1)
> >    as' <- get
> >    put (a:as')
> >    return r
> 


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



More information about the Beginners mailing list