20-CS-4003-001 Organization of Programming Languages Fall 2017
Monads

Lambda calculus, Type theory, Formal semantics, Program analysis

Prev     Next     All lectures           Code

Basics

f1 x = if (x == "hello") then Nothing 
       else (Just 10)

f2 x = if (x == 'a') then Nothing 
       else (Just 9)

add x y = 
  f1 x >>= (\x -> (f2 y) >>= 
  (\y -> return(x + y)))
  -   The same example as in the previous slide but now f1 and f2 are clearly pipelined in add. A failure at any point returns Nothing. Try this:
 Prelude> add "hello" 's'
 Nothing
 Prelude> add "bye" 's'
 Just 19
The type of add is still this:
 add :: Num b => [Char] -> Char -> Maybe b
If the return were not there the type of add would be this:
 add :: Num (Maybe b) => [Char] -> Char -> Maybe b
Using a Just instead of return works as well and gets add back to the proper return type.