Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop over a list of monadic values?

Tags:

haskell

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
like image 828
That Guy Avatar asked Sep 23 '21 15:09

That Guy


1 Answers

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
like image 73
flawr Avatar answered Oct 30 '22 12:10

flawr