\documentclass{beamer}
\usepackage{amsmath}
\usepackage{listings}
\usepackage{stmaryrd}

\title{Real World Haskell:\\
  Lecture 5}
\author{Bryan O'Sullivan}
\date{2009-11-04}

\begin{document}
\lstset{language=Haskell}

\frame{\titlepage}

\begin{frame}[fragile]
  \frametitle{Adding quaternions}
  
  We add two quaternions by adding their coefficients.

  \begin{align*}
    &&   a       &+{}& b\mathrm{i}       &+{}& c\mathrm{j} &+{}& d\mathrm{k} \\
    &+{}&w       &+{}& x\mathrm{i}       &+{}& y\mathrm{j} &+{}& z\mathrm{k} \\
    &={}&(a + w) &+{}& (b + x)\mathrm{i} &+{}& (c + y)\mathrm{j} &+{}& (d + z)\mathrm{k}
  \end{align*}

  \vskip8pt
  Or, in Haskell:
  \vskip8pt
\begin{lstlisting}
addQ (Q a b c d) (Q w x y z) =
  Q (a+w) (b+x) (c+y) (d+z)
\end{lstlisting}
\end{frame}

\begin{frame}[fragile]
  \frametitle{Subtracting quaternions}
  Subtraction is defined similarly.

\begin{lstlisting}
subQ (Q a b c d) (Q w x y z) =
  Q (a-w) (b-x) (c-y) (d-z)
\end{lstlisting}
\end{frame}

\begin{frame}[fragile]
  \frametitle{Typeclass inheritance}
  
  The \lstinline{Eq} typeclass that we met last week lets us compare
  values for equality.

  \vskip8pt For many values, we want to be able to compare them for
  (total) ordering, for which we use the \lstinline{Ord}
  typeclass.

  \vskip8pt
\begin{lstlisting}
class (Eq a) => Ord a where
  compare :: a -> a -> Ordering
\end{lstlisting}

  \vskip8pt Notice the constraint on the \lstinline{Ord} class: this
  states that in order for a type to be an instance of
  \lstinline{Ord}, it must already be an instance of \lstinline{Eq}.
\end{frame}

\begin{frame}[fragile]
  \frametitle{The \lstinline{Num} typeclass}

  Haskell defines a typeclass named \lstinline{Num} that lets us
  express common arithmetic operations:

\begin{lstlisting}
class (Eq a, Show a) => Num a where
  (+)    :: a -> a -> a
  (*)    :: a -> a -> a
  (-)    :: a -> a -> a
  negate :: a -> a
  abs    :: a -> a
  {- etc. -}
\end{lstlisting}
\end{frame}

\begin{frame}[fragile]
  \frametitle{\lstinline{Num} and quaternions}
  
  On first glance, we can easily fit our Quaternion type into the
  \lstinline{Num} class.

\begin{lstlisting}
instance Num Quaternion where
  (+) = addQ
  (-) = subQ
  {- ??? -}
\end{lstlisting}

  We quickly run into problems: it's not obvious what
  \lstinline{negate} or \lstinline{abs} should do.

  \vskip8pt Maybe we can do something with multiplication, though?
\end{frame}

\begin{frame}
  \frametitle{Multiplying quaternions}

  If we can remember the identities
  \begin{equation*}
    \mathrm{i}^2 = \mathrm{j}^2 = \mathrm{k}^2 = \mathrm{i} \mathrm{j}
    \mathrm{k} = -1
  \end{equation*}

  Then multiplication of quaternions falls out from the usual
  laws of arithmetic, but takes a complicated form:
  \begin{align*}
       a + b\mathrm{i}       + c\mathrm{j} + d\mathrm{k}
    *{} w + x\mathrm{i}       + y\mathrm{j} + z\mathrm{k}
    &={}aw - bx - cy - dz \\
    &+{}(ax + bw + cz - dy)\mathrm{i} \\
    &+{}(ay - bz + cw + dx)\mathrm{j} \\
    &+{}(az + by - cx + dw)\mathrm{k}
  \end{align*}
\end{frame}

\begin{frame}[fragile]
  \frametitle{Multiplying quaternions in Haskell}
  
  It's easy to convert our equation into executable form:
\begin{lstlisting}
mulQ (Q a b c d) (Q w x y z)
  = Q (a*w - b*x - c*y - d*z)
      (a*x + b*w + c*z - d*y)
      (a*y - b*z + c*w + d*x)
      (a*z + b*y - c*x + d*w)
\end{lstlisting}

  \pause \vskip8pt Does this mean that we should augment our
  definition of \lstinline{Num} as follows?
\begin{lstlisting}
instance Num Quaternion where
  (*) = mulQ
  {- etc. -}
\end{lstlisting}
\end{frame}

\begin{frame}
  \frametitle{Arithmetic laws}

  There are some laws that are so ingrained into our minds that we
  never think about them:
  \begin{align*}
    m + n &= n + m & \text{(commutative law of addition)} \\
    (m + n) + k &= m + (n + k) & \text{(associative law of addition)} \\
    mn &= nm & \text{(commutative law of multiplication)} \\
    (mn)k &= m(nk) & \text{(associative law of multiplication)} \\
  \end{align*}
\end{frame}

\begin{frame}[fragile]
  \frametitle{Laws for quaternions}
  
  We can see by simple inspection that addition over quaternions must
  satisfy the commutative and associative laws of normal arithmetic.

  \vskip8pt We used those familiar arithmetic laws to derive the
  formula for quaternion multiplication, but do quaternions satisfy
  the commutative law of multiplication?

\begin{verbatim}
Prelude> let a = Q 2 0 9 0
Prelude> let b = Q 0 9 0 2

Prelude> a `mulQ` b
Q 0.0 36.0 0.0 (-77.0)

Prelude> b `mulQ` a
Q 0.0 0.0 0.0 85.0
\end{verbatim}
\end{frame}

\begin{frame}
  \frametitle{Laws: made to be broken?}
  
  When you write or use a typeclass, there's an implied understanding
  that you'll obey its laws\footnote{Unfortunately, these laws are
    often undocumented.}.

  \vskip8pt Code that uses \lstinline{Eq} relies on the fact that if
  \lstinline{a == b} is \lstinline{True}, then \lstinline{b == a} will
  be \lstinline{True} too, and \lstinline{a /= b} will be
  \lstinline{False}.

  \vskip8pt Similarly, code that uses \lstinline{Num} implicitly
  relies on the commutativity and associativity of addition and
  multiplication.

  \pause \vskip8pt Neither the type system nor any other aspect of
  Haskell will help you to do the heavy lifting here:
  \begin{itemize}
  \item The burden is on \emph{you}, the creator of a type, to ensure
    that if you make it an instance of a typeclass, that it follows
    the laws.
  \end{itemize}
\end{frame}

\begin{frame}[fragile]
  \frametitle{A sketchy approach}
  
  Since quaternion multiplication is not commutative, we should not
  implement \lstinline{(*)}.  But what more should we do?
  
  \vskip8pt For instance, we could \emph{partially} implement
  \lstinline{Num}:

\begin{lstlisting}
instance Num Quaternion where
    (+) = addQ
    (*) = undefined
\end{lstlisting}

  What effect does this have on code that tries to use multiplication?
\begin{verbatim}
Prelude> scalar 2 * scalar 3
*** Exception: Prelude.undefined
\end{verbatim}

  \vskip8pt This is not very satisfactory behaviour.
\end{frame}

\begin{frame}[fragile]
  \frametitle{Playing fast and loose}
  
  Of course, Haskell itself doesn't escape the sin bin.  What happens
  to those fancy laws in the presence of inexact arithmetic?

\begin{verbatim}
Prelude> let a = 1e20 :: Double
Prelude> (a + (-a))   + 1
1.0
Prelude> a +   ((-a) + 1)
0.0
\end{verbatim}

  (This is the same behaviour as every other language that implements
  floating point, by the way.)

  \vskip8pt A conclusion? You can violate the rules, but the compiler
  can't remind you that you're cheating.
\end{frame}

\begin{frame}[fragile]
  \frametitle{Code that might fail}
  
  You've probably seen this behaviour by now:

\begin{verbatim}
Prelude> 1 `div` 0
*** Exception: divide by zero
\end{verbatim}

  These exceptions are often annoying, because we can't easily catch
  and handle them.  

  \vskip8pt There exists a predefined type we can use to
  deal with these cases:

\begin{lstlisting}
data Maybe a = Nothing
             | Just a
\end{lstlisting}

  Notice that this type is \emph{parameterized}, so we can have types
  such as \lstinline{Maybe Int}, or \lstinline{Maybe (String, Bool)},
  or so on.
\end{frame}

\begin{frame}[fragile]
  \frametitle{Safer functions via \lstinline{Maybe}}
  
  Safer integer division:

\begin{lstlisting}
a `safeDiv` 0 = Nothing
a `safeDiv` b = Just (a `div` b)
\end{lstlisting}

  \vskip8pt A safer version of \lstinline{head}:
\begin{lstlisting}
safeHead []    = Nothing
safeHead (x:_) = Just x
\end{lstlisting}
\end{frame}

\begin{frame}[fragile]
  \frametitle{Exercise time!}

  You should be familiar with the \lstinline{map} function by now:

\begin{lstlisting}
map :: (a -> b) -> [a] -> [b]
\end{lstlisting}

  \vskip8pt Write the equivalent function for the \lstinline{Maybe} type:
\begin{lstlisting}
mapMaybe :: (a -> b) -> Maybe a -> Maybe b
\end{lstlisting}
\end{frame}

\begin{frame}[fragile]
  \frametitle{Binary trees}
  
\begin{lstlisting}
data Tree a = Empty
            | Node a (Tree a) (Tree a)
              deriving (Eq, Ord, Show)

leaf v = Node v Empty Empty

someOldTree =
  Node "quux" (leaf "foo") 
       (Node "eek" (leaf "bar") 
             (Node "zip" (leaf "baz") Empty))
\end{lstlisting}
\end{frame}

\begin{frame}[fragile]
  \frametitle{Sizing a tree}
  
\begin{lstlisting}
size Empty      = 0
size Node _ a b = 1 + size a + size b
\end{lstlisting}
\end{frame}

\begin{frame}[fragile]
  \frametitle{Mapping again}
  
  What should this function look like?

\begin{lstlisting}
mapTree :: (a -> b) -> Tree a -> Tree b
\end{lstlisting}
\end{frame}

\begin{frame}[fragile]
  \frametitle{Generalising mapping}
  
  So far, we've seen three different container types, with three
  different map-like functions:

\begin{lstlisting}
map      :: (a -> b) -> [a]     -> [b]
mapMaybe :: (a -> b) -> Maybe a -> Maybe b
mapTree  :: (a -> b) -> Tree a  -> Tree b
\end{lstlisting}

  \vskip8pt It turns out we can write a typeclass to generalise this
  idea:

\begin{lstlisting}
class Functor f where
    fmap :: (a -> b) -> f a -> f b

instance Functor Maybe where 
    fmap = mapMaybe
\end{lstlisting}
\end{frame}
\begin{frame}[fragile]
  \frametitle{Homework---binary search trees}
  
  Turn the \lstinline{Tree} type into a binary search tree by defining
  the following functions:

\begin{lstlisting}
insert :: (Ord a) => a -> Tree a -> Tree a
contains :: (Ord a) => a -> Tree a -> Bool
\end{lstlisting}
\end{frame}

\begin{frame}[fragile]
  \frametitle{Homework---key/value containers}

  Adapt your binary search tree code for use to create a simple
  key/value container:
\begin{lstlisting}
type Map a b = Tree (a,b)
insertItem 
  :: (Ord a) => a -> b -> Map a b -> Map a b
lookupByKey 
  :: (Ord a) => a -> Map a b -> Maybe b
listToMap 
  :: (Ord a) => [(a,b)] -> Map a b
mapToList
  :: Map a b -> [(a,b)]
minItem
  :: (Ord a) => Map a b -> Maybe (a,b)
\end{lstlisting}
\end{frame}
\end{document}

%%% Local Variables: 
%%% mode: latex
%%% TeX-master: t
%%% TeX-PDF-mode: t
%%% End: 

