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

Lambda calculus, Type theory, Formal semantics, Program analysis

    Prev     Next     All lectures           Code

Monads for Exception Handling

import Prelude hiding (lookup)
import Data.Map

  = fromList([("John","Sales"), ("Bob","IT")])
  = fromList([("IT","USA"), ("Sales","France")])
  = fromList([("USA", "Dollar"), ("France", "Euro")])

dept Nothing = Nothing
dept (Just name) = lookup name employeeDeptDB

country Nothing = Nothing
country (Just dpt)  = lookup dpt deptCountryDB

currency Nothing = Nothing
currency (Just cty) = lookup cty countryCurrencyDB

down Nothing = ""
down (Just x) = x

employeeCurrency name = currency $ country $ dept (Just name)

v1 = down $ employeeCurrency "John"  {- "John" -}
v2 = down $ employeeCurrency "Bob"   {- "Bob" -}
v3 = down $ employeeCurrency "Skip"  {- "" -}
  -   Use of Maybe Monad to recover from errors where errors are expected.

A functions whose output is not specified for all inputs is a partial function. A total function has deterministic output for all inputs. In pure functional programming, total functions are required. But, some functions normally are partial. Such a partial function may be made total by changing its return type to a Maybe.

This trick of returning a different type in order to turn a non-functional computation into a pure function is used extensively in Haskell and finds its full expression in monads.

Code to the left makes use of the following:

fromList :: Ord k => [(k, a)] -> Map k a
Which builds a map from a list of key/value pairs.
lookup :: Ord k => k -> Map k a -> Maybe a
Which looks up the value associated with a key in the input map. The corresponding value returned is a (Just value) or Nothing if the key is not in the map.