Home > Software design >  How to loop over a list of monadic values?
How to loop over a list of monadic values?

Time:09-24

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

CodePudding user response:

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
  • Related