[Haskell-beginners] Using StateT with List monad
Brent Yorgey
byorgey at seas.upenn.edu
Sat Nov 24 16:15:49 CET 2012
On Sat, Nov 24, 2012 at 02:52:42PM +0100, Nathan Hüsken wrote:
> Hey,
>
> I have an example function in the list monad.
>
> twoSucc :: Int -> [Int]
> twoSucc i = [i+1, i+2]
>
> Now I want write something similar with the StateT monad transformer.
>
> twoSucc :: StateT Int [] ()
> twoSucc = do
> i <- get
> put (i+1) -- how do I put [i+1,i+2] here?
>
> As mentioned in the comment, when doing
>
> runStateT twoSucc n
>
> it outputs [((),n+1)] (which makes sense). How do I write it that it
> behaves similar to the original twoSucc and outputs [((),n+1),((),n+2)]?
StateT Int [] is an instance of MonadPlus which gives you access to
the nondeterminism of the list monad. So you can do
twoSucc :: StateT Int [] ()
twoSucc = do
i <- get
put (i+1) `mplus` put (i+2)
Intuitively, mplus splits the computation into two independent
parallel branches.
-Brent
More information about the Beginners
mailing list