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

\title{Real World Haskell:\\
  Lecture 4}
\author{Bryan O'Sullivan}
\date{2009-10-29}

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

\frame{\titlepage}

\begin{frame}
  \frametitle{Quaternions}
  
  A quaternion is a mathematical structure, ``the extension of complex
  numbers to three dimensions.''

  \vskip8pt

  In mathematical notation, some people write a quaternion
  $\mathbf{q}$ as follows:
  \begin{equation*}
    \mathbf{q} = a + b\mathrm{i} + c\mathrm{j} + d\mathrm{k}
  \end{equation*}

  \vskip12pt

  The $\mathrm{i}$, $\mathrm{j}$, and $\mathrm{k}$ terms (the
  \emph{basis elements}) are related to the $\iota$ of complex
  numbers, and have similarly weird properties:

  \begin{equation*}
    \mathrm{i}^2 = \mathrm{j}^2 = \mathrm{k}^2 = \mathrm{i} \mathrm{j}
    \mathrm{k} = -1
  \end{equation*}
\end{frame}

\begin{frame}
  \frametitle{What are quaternions \emph{for}?}
  
  \begin{itemize}
  \item Invented in 1843 by William Rowan Hamilton. 
  \item Briefly used in 19th-century physics, e.g. in the description
    of Maxwell's equations that related electric and magnetic fields
    to charge density and current density.
  \item Lost favour in the 1890s, supplanted by vector analysis.
  \item Recently popular again, due to utility in describing rotations.
  \end{itemize}

  \vskip8pt
  Current uses include:
  \begin{itemize}
  \item Computer graphics (smoothly interpolated rotations)
  \item Signal processing (image disparity, e.g. in geophysics)
  \item Attitude control (e.g. in spacecraft)
  \item Orbital mechanics
  \item Simulation of molecular dynamics
  \end{itemize}
\end{frame}

\begin{frame}[fragile]
  \frametitle{What's this got to do with Haskell?}
  
  The set $\mathbb{H}$ of quaternions is equal to $\mathbb{R}^4$ (a 4d
  vector space over the reals), so we could conceivably use a
  representation like this:

  \vskip8pt

\begin{lstlisting}
type Quaternion =
     (Double, Double, Double, Double)
\end{lstlisting}

  \vskip8pt

  Quaternions are \emph{not} arbitrary 4-vectors; they have special
  properties.

  \vskip8pt

  So why might we \emph{not} want to use this definition?
  \begin{itemize}
  \item Since \lstinline{Quaternion} is simply a synonym for a 4-tuple
    of \lstinline{Double}s, the compiler will treat the two types as the
    same, even when \emph{our intended meaning} is distinct.
  \end{itemize}
\end{frame}

\begin{frame}[fragile]
  \frametitle{Giving types more structure}
  
  We conclude that we want a quaternion to somehow ``look different''
  from a 4-tuple.  Here's how we can do it:

  \vskip8pt

\begin{lstlisting}
data Quaternion =
     Q Double Double Double Double
\end{lstlisting}

  \vskip8pt

  The \lstinline{data} directive introduces a \emph{completely new
    type} named \lstinline{Quaternion}.

  \vskip8pt

  We call the name that follows the \lstinline{data} directive the
  \alert{type constructor}: it identifies the type.

\end{frame}

\begin{frame}[fragile]
  \frametitle{Data constructors}

\begin{lstlisting}
data Quaternion =
     Q Double Double Double Double
\end{lstlisting}

  \vskip8pt

  Following the ``\lstinline{=}'' sign above is the name
  \lstinline{Q}, which is a \alert{data constructor} for the
  \lstinline{Quaternion} type.

  \vskip8pt

  We use a data constructor to \emph{build a new value} of a given
  type.

  \vskip8pt

  Type constructors create types.  Data constructors create values.
\end{frame}

\begin{frame}[fragile]
  \frametitle{Using constructors (I)}

  \vskip8pt

  The 4 instances of \lstinline{Double} following the \lstinline{Q}
  are the \emph{type parameters} to that data constructor.

  \vskip8pt

  When we use our data constructor, we need to supply values:
  \begin{itemize}
  \item The number of values must match the number of type parameters.
  \item The type of each value must match the type parameter at that
    position.
  \end{itemize}

  \vskip8pt
  We have a simple case here: just plug in four numbers.
\begin{lstlisting}
zero = Q 0 0 0 0
\end{lstlisting}
\end{frame}

\begin{frame}[fragile]
  \frametitle{Using constructors (II)}

  Remember the data constructors for lists?

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

  \pause
  \vskip8pt
  We use \emph{data constructors} to create new values.

\begin{lstlisting}
foo = 'f' : 'o' : 'o' : []
\end{lstlisting}

  \pause
  \vskip8pt
  We use \emph{type constructors} in type signatures.
\begin{lstlisting}
stripLeft :: [Char] -> [Char]
\end{lstlisting}
  \pause
  \vskip8pt

  We pattern match \emph{against} data constructors to inspect a value.

\begin{lstlisting}
stripLeft (x:xs) | isSpace x = stripLeft xs
                 | otherwise = x : xs
stripLeft []                 = []
\end{lstlisting}
\end{frame}

\begin{frame}[fragile]
  \frametitle{Using data constructors (III)}
  
  We do the same with our new \lstinline{Quaternion} type.

  \vskip8pt

  Here's a type signature for the function that creates a
  scalar-valued quaternion.  Notice the use of the type constructor.

\begin{lstlisting}
scalar :: Double -> Quaternion
\end{lstlisting}

  \vskip8pt And here's the definition of the \lstinline{scalar}
  function, where we use the data constructor to create a new
  value of type \lstinline{Quaternion}.
\begin{lstlisting}
scalar s = Q s 0 0 0
\end{lstlisting}
\end{frame}

\begin{frame}[fragile]
  \frametitle{Using data constructors (IV)}
  We perform pattern matching as you might expect:

\begin{lstlisting}
scalarPart :: Quaternion  -> Double
scalarPart    (Q s _ _ _) =  s
\end{lstlisting}

  \vskip12pt

  The special pattern ``\lstinline{_}'' above has the following
  meaning:
  \begin{itemize}
  \item ``I don't care what's at this position.  Don't inspect the
    value here, and don't bind it to a name.''
  \item In other words, it's a \emph{wild card}.
  \end{itemize}

  \pause \vskip8pt Notice that we had to provide four patterns after
  the \lstinline{Q}, one to match each of the \lstinline{Q}
  constructor's parameters.
\end{frame}

\begin{frame}[fragile]
  \frametitle{Spelunking with the interpreter}
  We can usefully inspect our new type in \texttt{ghci}:
\begin{verbatim}
Prelude> :info Quaternion
data Quaternion = Q Double Double Double Double
  	-- Defined at Quaternion.hs:1:5-14
\end{verbatim}
  The \texttt{:info} command is very useful! It tells us everything
  \texttt{ghci} knows about an identifier (regardless of whether it's
  a type, a function, or whatever).

  \pause
  \vskip12pt
  We can also inspect the type of the \lstinline{Q} data constructor:
\begin{verbatim}
Prelude> :type Q
Q :: Double -> Double -> Double -> Double
  -> Quaternion
\end{verbatim}
\end{frame}

\begin{frame}[fragile]
  \frametitle{What does this correspond to?}
  
  Are you struggling to follow so far?

  \pause \vskip12pt Here's an approximate equivalent to what we just
  covered, in a familiar language:
\begin{verbatim}
struct quaternion {
    double a, b, c, d;
};
\end{verbatim}

  \pause \vskip8pt And here's another, in a different (but still
  familiar) language:
\begin{verbatim}
class Quaternion(object):
    def __init__(self, a,b,c,d):
        self.a,self.b,self.c,self.d = a,b,c,d
\end{verbatim}
\end{frame}

\begin{frame}[fragile]
  \frametitle{Comparing quaternions}
  
  We're used to being able to compare values.
\begin{lstlisting}
("foo" == "bar", "baz" /= "quux")
  ==> (False, True)
\end{lstlisting}

  \vskip8pt So how should we compare quaternions?  This definition
  won't compile:

\begin{lstlisting}
wtf = scalar 1 == scalar 2
\end{lstlisting}

  \vskip8pt Ugh, okay. Let's try this:
\begin{lstlisting}
equals (Q a b c d) (Q w x y z) =
  a == w && b == x && c == y && d == z
\end{lstlisting}
\end{frame}

\begin{frame}[fragile]
  \frametitle{Notational aside: functions and operators}

  Functions and operators are the same, save for fixity.  We usually
  apply functions in prefix position, and operators in infix position.

  \vskip8pt However, we can treat an operator as a function by
  wrapping it in parentheses:
\begin{lstlisting}
(+)  1  2
(:) 'a' []
zipWith (+) [1,2,3] [4,5,6]
\end{lstlisting}

  \vskip8pt We can also apply a function as if it was an operator, by
  wrapping it in backquotes:
\begin{lstlisting}
scalar 1 `equals`     scalar 2
"wtf"    `isPrefixOf` "wtfbbq"
\end{lstlisting}
\end{frame}

\begin{frame}[fragile]
  \frametitle{But still\ldots\,\emph{ugh!}}
  
  It seems lame that we can write this for strings:
\begin{lstlisting}
"foo" == "bar"
\end{lstlisting}

  \vskip8pt And, even with our shiny new infix syntax, find ourselves
  stuck writing code like this for quaternions:
\begin{lstlisting}
scalar 2 `equals` scalar 3.14159265
\end{lstlisting}

  \vskip8pt Surely there's some kind of unifying principle we could
  put to work?
\end{frame}

\begin{frame}[fragile]
  \frametitle{Enter the typeclass}
  
  Here is a definition of a widely used typeclass:

\begin{lstlisting}
class Eq a where
    (==) :: a -> a -> Bool
\end{lstlisting}

  The definition says ``there is a class of types that support a
  function named \lstinline{(==)}.''

  \pause \vskip12pt How can we declare a type as being a member of
  this \lstinline{Eq} class?
\begin{lstlisting}
instance Eq Quaternion where
    (==) = equals
\end{lstlisting}
This means ``any time someone asks for the \lstinline{(==)} function on
\lstinline{Quaternion} type, use the \lstinline{equals} function.''
\end{frame}

\begin{frame}[fragile]
  \frametitle{Use of \lstinline{(==)}}
  
  As we know, we can use the \lstinline{(==)} operator when writing
  functions:

\begin{lstlisting}
elem a []       = False
elem a (x:xs)
    | a == x    = True
    | otherwise = elem a xs
\end{lstlisting}

  \vskip12pt
  Notice something very important: 
  \begin{itemize}
  \item This function needs to know almost nothing about the type of
    the values \lstinline{a} and \lstinline{x}.
  \item It's enough to know that the type supports the
    \lstinline{(==)} function, i.e. that it's an instance of the
    \lstinline{Eq} typeclass.
  \end{itemize}
\end{frame}

\begin{frame}[fragile]
  \frametitle{Bounded polymorphism}
  
  The \lstinline{elem} function is clearly polymorphic, but it's not
  \emph{fully} polymorphic. 
  \begin{itemize}
  \item It will work for any instance of \lstinline{Eq}.
  \item However, it will \emph{not} work on types that are not
    instances of \lstinline{Eq}, since they don't supply an
    implementation of \lstinline{(==)}.
  \item So our function exhibits a special kind of polymorphism called
    \emph{bounded} (or \emph{constrained}) polymorphism.
  \end{itemize}
\end{frame}

\begin{frame}[fragile]
  \frametitle{Expressing bounded polymorphism}

  \vskip8pt We can express the fact that \lstinline{elem} only accepts
  instances of \lstinline{Eq} in its type signature:

\begin{lstlisting}
elem :: (Eq a) => a -> [a] -> Bool
\end{lstlisting}

  The ``\lstinline{(Eq a) =>}'' part of the signature is called a
  \emph{constraint}.

  \vskip8pt In the absence of a type signature, a Haskell compiler
  will infer the presence of any necessary constraints.

  \pause
  \vskip24pt Aside: Haskell's kind of polymorphism is called
  \emph{parametric}.  In this type signature:

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

  The type of \lstinline{(++)} is \emph{parameterized} by the type
  variable \lstinline{a}.
\end{frame}

\begin{frame}[fragile]
  \frametitle{Rainbows, oh my!}
  
  Suppose we want to refer to symbolic values.
\begin{lstlisting}
data Rainbow = Red  | Orange | Yellow | Green
             | Blue | Indigo | Violet
\end{lstlisting}

  We have defined a type \lstinline{Rainbow} with a whole pile of data
  constructors.
  \begin{itemize}
  \item These constructors are all independent.
  \item If you're a C or C++ hacker, think of \lstinline{Rainbow} as
    an \emph{enumerated type} (\texttt{enum}).
  \item Each data constructor creates a value of type
    \lstinline{Rainbow}.
  \item We can pattern match against a value to see whether it is
    \lstinline{Green}, or \lstinline{Blue}, or whatever.
  \end{itemize}
\end{frame}

\begin{frame}[fragile]
  \frametitle{Showing your work}
  
  We haven't indicated how to print values from our new datatypes
  yet. Indeed, unless we do something explicit, we \emph{can't} print
  them.

  \vskip8pt Fortunately for us, there's a \lstinline{Show} typeclass,
  with a useful function:

\begin{lstlisting}
show :: (Show a) => a -> String
\end{lstlisting}

  \vskip8pt So.  What do we do?

\begin{lstlisting}
instance Show Rainbow where
    show Red   = "Red"
    show Green = "Green"
    {- ... etc ... -}
\end{lstlisting}
\end{frame}

\begin{frame}[fragile]
  \frametitle{Yeuch!}

  That's some serious drudgery there.  I hate repeating myself.

  \vskip8pt Fortunately, for some key typeclasses, Haskell can
  \emph{automatically derive} instances for us as follows.

  \vskip8pt
\begin{lstlisting}
data Rainbow = Red  | Orange | Yellow | Green
             | Blue | Indigo | Violet
     deriving (Eq, Ord, Bounded, Enum, Show)
\end{lstlisting}

  \vskip8pt This saves a lot of meaningless finger-plonkulating.
\end{frame}

\begin{frame}[fragile]
  \frametitle{Homework (I)---the trivial part}

  \vskip8pt Use \texttt{ghci} to investigate the \lstinline{Ord},
  \lstinline{Bounded}, and \lstinline{Enum} typeclasses.
\end{frame}

\begin{frame}
  \frametitle{Homework (II)}
  
  Three non-overlapping points in the plane $\mathbb{R}^2$ form either
  an acute angle ($< 180^\circ$), a straight line, or an obtuse angle
  ($> 180^\circ$).

  \vskip12pt

  Define a type that represents these possibilities.

  \vskip12pt

  Write a type signature for a function that accepts three points, and
  categorises them in this fashion.

  \vskip12pt

  Now write the function itself.
\end{frame}

\begin{frame}
  \frametitle{Homework (III)}

  In computational geometry, the convex hull of a set of
  non-overlapping points is the minimal bounding polygon for which all
  angles are acute.

  \begin{center}
    \includegraphics[height=1in]{convex-hull.png}
  \end{center}

  Using your categorisation function, write a function that computes
  the convex hull of a set of points.

  \vskip12pt

  (If you need a hint, look up ``Graham's scan algorithm''.)
\end{frame}
\end{document}

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

