Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Novice haskell - sequential monad binding

Tags:

haskell

I'm looking for the idiomatic way to do this. It works, but seems like I must be reinventing something in the standard library. What's the right way to do this?

I'm trying to pass a list of functions and bind them in sequence. Toy example:

bindSeq :: (Monad m) => m a ->  [(a -> m a)] -> m a
bindSeq m [] = m 
bindSeq m (x:xs) = bindSeq ( m >>= x ) xs

bindSeq (Just 4) [ Just . (+1), Just . (+2)]
Just 7
like image 217
Steve B. Avatar asked Jun 05 '26 07:06

Steve B.


1 Answers

As @Fixnum wrote in 2013, your bindSeq is foldl' (>>=)

But if you want to see this as an "effectful fold" over values, then you can just "put on m-colored glasses" and overlook the m, then look what's left. Absent the monadic effects, you want a signature: a -> [a -> a] -> a.

This is folding function application and can be written foldl (flip ($)).

So now, "promote" that to be effectful and we see the following:

Prelude Control.Monad> :t foldM (flip ($))
foldM (flip ($)) :: Monad m => a -> [a -> m a] -> m a

as desired!

like image 67
sclv Avatar answered Jun 07 '26 22:06

sclv



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!