log-book

Monads in Haskell

November 22, 2022, tags: haskell, monad.

Monads and Effects, 4

Influential papers

Monads, Arrows, and Idioms

  1. [Wad92a] P. Wadler. Comprehending monads.
  2. [Wad92b] P. Wadler. The essence of functional programming.
  3. [Wad95] P. Wadler. Monads for functional programming.

Implementing Monads in Haskell

The representation of monads in Haskell is based on the Kleisli triple formulation:

A Kleisli triple over a categroy π’ž is a triple (T,Ξ·,βˆ’*), where T : |π’ž| → |π’ž|, ηA : A → TA for Aβ€„βˆˆβ€„|π’ž|, f* : TA → TB for f : A → TB and the following equation hold: . . .

In Haskell, π’ž is the categroy which Haskell types as objects and Haskell functions as arrows, T corresponds to a parameterised type, Ξ· is called return, and βˆ’* is called >>==

return :: a -> T a
(>>=) :: (a -> T b) -> (T a -> T b)

In Haskell, return is used to wrap data in a monad. When speaking about I/O, return is used to take pure data and bring it into the IO monad.
–Real World Haskell, Chapter 7, I/O, The IO Monad

A useful way to link its behavior to its name is that it injects(returns) a pure value (of type a) into a monad (of type m a).
–Real World Haskell, Chapter 14, Monads, The Monad Typeclass

We can consider >>= to be a currried function of two arguments, with type (a -> T b) and T a.

We give >>= the type

(>>=) :: T a -> (a -> T b) -> T b

Now the metalanguage notation let x ⇐ e1 in e2 can be conveniently expressed as:

e1 >>= \x -> e2
  • \x -> e means Ξ»xe
  • this bind x to the result of e1 in e2;
  • >>= pronounced as β€œbind”
  • \x pronounced as β€œΞ» x”

This is Anonymous (lambda) function in Haskell. We introduce an anonymous function with a backslash character (\) pronounced lambda. (the backslash was chosen for its visual resemblance to the Greek letter Ξ».)
–Real World Haskell, Chapter 4, Functional Programming, Anonymous (lambda) Functions

Example