Using StateT with List monad

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)]? Thanks! Nathan

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

Hi,
On 24 November 2012 15:15, Brent Yorgey
twoSucc :: StateT Int [] () twoSucc = do i <- get put (i+1) `mplus` put (i+2)
Another way of doing the same thing, which I find more intuitive, is the following: twoSucc :: StateT Int [] () twoSucc = do i <- get j <- lift [i+1, i+2] put j -- Ozgur Akgun

On Sat, Nov 24, 2012 at 5:52 AM, Nathan Hüsken
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.
The simplest addition of StateT would look like this: twoSucc :: StateT () [] Int twoSucc i = lift [i+1, i+2]
twoSucc :: StateT Int [] () twoSucc = do i <- get put (i+1) -- how do I put [i+1,i+2] here?
In this transformation, you've moved your Int result from being the monadic result to being the stored state. I don't know which transformation you really want. -Karl
participants (4)
-
Brent Yorgey
-
Karl Voelker
-
Nathan Hüsken
-
Ozgur Akgun