Monads

The Monad typeclass is best understood by looking at it from many perspectives. That is why this book has no definitive section or chapter on Monad. Instead, we will successively peel off the layers of this abstraction.

Let's begin by looking at a simple example of interpreting expressions:

data Expr = Lit Int | Div Expr Expr

eval :: Expr -> Int
eval (Lit a) = a
eval (Div a b) = eval a `div` eval b

The eval function interprets expressions written in our Expr data type:

(eval (Lit 42))                 –- 42
(eval (Div (Lit 44) (Lit 11)))  -- 4

Stripped of real-world concerns, this is very elegant. Now let's add (naive) capability to deal with errors in our interpreter. Instead of the eval function returning integers, we'll return a Try data type, which caters ...

Get Haskell Design Patterns now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.