HfT 01 02 03 04 05 06     01 02 03 04 05 06 07 08 09 10        

Monads

module Main where

We begin by defining a plain wrapper, that does nothing besides get in our way.

data M a = M a deriving Show

The operator composes two functions whose return values are wrapped by M. For comparison, recall the type of (.).

(.)  (b  c)  (a  b)  a  c
infixr 9 

()  (b  M c)  (a  M b)  a  M c
() p q x = p y where M y = q x

Note that M wraps its argument. We can think of M as a wrapped identity function; M is the identity element for the composition law .

M  a  M a

f and g are wrapped functions.

f, g  String  M String

f x = M ('F' : x)
g x = M ('G' : x)

main  IO ()
main = mapM_ (print . ($ "x"))
   [ M
   , f  M
   , M  f
   , f  g
   , g  f
   , f  M  g
   ]
M "x"
M "Fx"
M "Fx"
M "FGx"
M "GFx"
M "FGx"

Main.hs