Week 8: Notes

Maybe

For any type t, a value of type Maybe t is either Just x (where x has type t) or Nothing. For example, Just 4, Just 0 and Nothing are all possible values of type Maybe Int.

So the constant Nothing is something like null or None in other languages: it represents the absence of a value. When we write a function that might succeed or fail, we will often make its return type be Maybe t for some type t. Then the function will return a Just if it succeeds, otherwise Nothing.

For example, here's a function that will look up a key in an association list, i.e. a list of key-value pairs. If it finds the key, it will return the associated value; otherwise it returns Nothing.

lookup :: Eq a => a -> [(a, b)] -> Maybe b
lookup _ [] = Nothing
lookup x ((k, v) : rest)
    | x == k = Just v
    | otherwise = lookup x rest

Let's try it:

> d = [('x', 3), ('y', 5), ('z', 7)]
> lookup 'y' d
Just 5
> lookup 'q' d
Nothing

In fact this function is built into Haskell's standard library.

case expressions
higher-order functions
lambda expressions
curried functions
operator sections
function composition

You can read about these subjects in Learn You a Haskell, chapters 4 - 6.