That Guy
That Guy

Reputation: 2399

How to loop over a list of monadic values?

Say I have a list of 3 values: es = [MyMonad 33, MyMonad 55, MyMonad 88]. Then I would perform

do v1 <- funcReturningMyMonad (es !! 0)
   v2 <- funcReturningMyMonad (es !! 1)
   v3 <- funcReturningMyMonad (es !! 2)
   funcTakingListOfInts [v1,v2,v3]

My problem is that I would like to somehow achieve this behavior for a list of arbitrary length n. In the above case n was 3. I thought about calling (>>=) sequentially through the list but it doesn't add up. How would you achieve this behavior?

Function types:

funcReturningMyMonad :: MyMonad Int -> MyMonad Int
funcTakingListOfInts :: [Int] -> MyMonad Int

Upvotes: 5

Views: 125

Answers (1)

flawr
flawr

Reputation: 11628

Since

funcReturningMyMonad :: MyMonad Int -> MyMonad Int

we can use

mapM :: (Traversable t, Monad m) => (a -> m b) -> t a -> m (t b)  

for the first part, which in our case will be

 (MyMonad Int -> MyMonad Int) -> [MyMonad Int] -> MyMonad [Int]

then we can use the bind operator for applying funcTakingListOfInts so you'd end up with:

(mapM funcReturningMyMonad es) >>= funcTakingListOfInts

Upvotes: 7

Related Questions