🎓 A1Learner
🔍
0 of 50 lessons completed

Haskell Monad Laws

The Monad laws are three equalities that every Monad instance must satisfy. They state that return is neutral and that bind grouping does not change the result.

Left identity holds for doubling

Binding return 3 into the doubling step equals doubling 3 directly. Both sides give Just 6.

f :: Int -> Maybe Int
f x = Just (x * 2)
main :: IO ()
main = print ((return 3 >>= f) == f 3)

Right identity holds for a Just value

Binding Just 7 with return gives back Just 7. The equality test therefore prints True.

main :: IO ()
main = print ((Just 7 >>= return) == Just 7)

Associativity holds for two steps

Grouping the binds on the left or on the right gives the same result. Both sides give Just 40.

f :: Int -> Maybe Int
f x = Just (x + 1)
g :: Int -> Maybe Int
g x = Just (x * 10)
main :: IO ()
main = print (((Just 3 >>= f) >>= g) == (Just 3 >>= (\x -> f x >>= g)))

Example

f :: Int -> Maybe Int
f x = Just (x + 1)
g :: Int -> Maybe Int
g x = Just (x * 10)
main :: IO ()
main = do
  print ((return 3 >>= f) == f 3)
  print ((Just 7 >>= return) == Just 7)
  print (((Just 3 >>= f) >>= g) == (Just 3 >>= (\x -> f x >>= g)))

Key points

  • Left identity: binding return of a value is the same as applying the function directly.
  • Right identity: binding a wrapped value with return gives back the same wrapped value.
  • Associativity: regrouping two binds in a chain gives the same final result.
  • Use the laws to check that a custom Monad instance behaves like a proper chain.
  • Equality test: the == operator that compares two wrapped values and gives True or False.

In this example, the first line checks left identity and the second line checks right identity. The third line checks associativity, and all three lines print True.

Note

A law that fails means the instance is not a lawful Monad.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Haskell Playground

Exercise

Which equality states left identity?