Home > OS >  (Haskell) Syntax for chaining functions with bindings in do block
(Haskell) Syntax for chaining functions with bindings in do block

Time:07-20

I have the following code that chains functions using a monad, binding the intermediate results.

r :: Int -> Maybe Int
r n = do
  r1 <- f1 n
  r2 <- f2 r1
  r3 <- f3 r2
  r4 <- f4 r3
  return r4

where the type signature of the f1-f4 is f1 :: Int -> Maybe Int.

The code works, however I would like to avoid naming the intermediate results (r1-r4).

If I wasn't working with monads, I could simply write r = f1 . f2 . f3 . f4. Is something similar possible for monads?

CodePudding user response:

(.) is composition for regular arrows (a -> b). (>=>) is composition for Kleisli arrows (a -> m b).

import Control.Monad

r :: Int -> Maybe Int
r = f1 >=> f2 >=> f3 >=> f4
  • Related