monad

Table of Contents

A monad is defined as a typeclass which supports the following three operations

See the monad laws for axioms relating to these three operations.

The way to think of m a is really as a computation that results in a. For instance, IO String reflects a String obtained via an IO-dependent computation.

In the same sense, monads are about organizing "dependencies" by creating a one-way gate for pure values.

Monadic operations may be composed via kleisli composition.

1. Do-syntax for monads in haskell

Plain statements must be monadic actions. The last statement in the do block should be a monadic action that matches the signature of the function.

f :: IO ()
f = do putStrLn "Hello World"

Bind is accomplished with <-

f :: IO ()
f = getLine >>= putStrLn . reverse
f' = do
  l <- getLine
  putStrLn (reverse x)

The two are equivalent.

The let keyword implicitly composes a function with return and binds it.

f :: IO ()
f = do
  l <- getLine
  let r = reverse l
  -- r <- (return . reverse) l
  putStrLn r

r is still of type \(IO String\). Allows applying pure -> pure functions with monadic values to yield monadic values.

Back to index