CSCE 314 Lecture 18

From Notes
Jump to navigation Jump to search

« previous | Friday, October 7, 2011 | next »


What is a Monad?

a strategy for combining computations into more complex computations

Laws of Monads

(return a) >>= f == f a                    -- symmetry, identity
m >>= return == m

(m >>= f) >>= g == m >>= (\x -> f x >>= g) -- associativity

IO Monads

IO is a monad, but it makes all functions that contain it IO monads:

IO takes an IO argument and returns an IO argument.

  • return offers a way in to an IO, but there is no way out
  • It's possible to implement a way out, but it's very unsafe...

A complete Haskell "main" program is a single IO action.


Error Handling

Haskell has a Maybe type constructor:

data Mabye a = Just a | Nothing

We can use this in a "partial" function to represent success or failure:

doQuery :: Query -> DB -> maybe Record

r :: Maybe Record
r = case doQuery q1 db of
    Nothing -> Nothing
    Just r1 -> case doQuery (q2 r1) db of
        Nothing -> Nothing
        Just r2 -> case doQuery (q3 r2) db of
            Nothing -> Nothing
            Just r3 -> case ...

We can capture the pattern of the above function into a combinator:

thenMB :: Maybe a -> (a -> Maybe b) -> Maybe b
mB `thenMB` f = case mB of
    Nothing -> Nothing
    Just a -> f a

THen the querying function looks like:

r :: Maybe Record
r = doQuery q1 db `thenMB` \r1 ->
    doQuery (q2 r1) db `thenMB` \r2 ->
    doQuery (q3 r2) db `thenMM` \r3 ->
    ...

Given thenMB, we can make Mabye a monad:

instance Monad Mabye where
    (>>=) = thenMB
    return = Just