Haskell Monad Class
The Monad class is a typeclass for chaining steps that each produce a wrapped value. It lets one step feed its result into the next step.
Bind feeds a wrapped value into the next step
The function adds 3 inside Maybe. The printed result shows the wrapped sum.
main :: IO ()
main = print (Just 2 >>= (\x -> Just (x + 3)))Return wraps a plain value
Return places 5 inside Maybe. Pure gives the same wrapped value.
main :: IO ()
main = do
print (return 5 :: Maybe Int)
print (pure 5 :: Maybe Int)Bind chains two steps in order
The first step doubles 10. The second step adds 1 to that result.
main :: IO ()
main = print (Just 10 >>= (\x -> Just (x * 2)) >>= (\y -> Just (y + 1)))Example
doubleIfPositive :: Int -> Maybe Int
doubleIfPositive x = if x > 0 then Just (x * 2) else Nothing
main :: IO ()
main = print (Just 5 >>= doubleIfPositive >>= (\y -> Just (y + 3)))Key points
- Monad: a typeclass for values wrapped in a context such as Maybe or a list.
- Bind: the operator that feeds a wrapped value into a function returning a wrapped value.
- Use bind to chain steps where each step can fail or produce many results.
- Return: the function that wraps a plain value with no extra effect.
- Use return to place a plain value into the same wrapper as the other steps.
In this example, Just 5 enters doubleIfPositive and becomes Just 10. Then bind adds 3 inside Maybe and the program prints Just 13.
Note
In Haskell return and pure give the same result for the same wrapper.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Haskell Playground
Exercise
What is Just 2 >>= (\x -> Just (x + 3))?