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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With