\documentclass{book}
\renewcommand{\chaptername}{Lecture}
\usepackage{amsmath}
\usepackage{ctable}
\usepackage[mathletters]{ucs}
\usepackage[utf8x]{inputenc}
% Redefine labelwidth for lists; otherwise, the enumerate package will cause
% markers to extend beyond the left margin.
\makeatletter\AtBeginDocument{%
  \renewcommand{\@listi}
    {\setlength{\labelwidth}{4em}}
}\makeatother
\usepackage{enumerate}
\usepackage[breaklinks=true,unicode=true]{hyperref}
\setlength{\parindent}{0pt}
\setlength{\parskip}{6pt plus 2pt minus 1pt}
%\setcounter{secnumdepth}{0}


\begin{document}

\setcounter{chapter}{7}

\chapter{An expression evaluator}

Our goal is to build a simple calculator. We will not worry about the
parsing as that requires input output for which we are not ready yet. We
will only build the expression evaluator. We start by defining a data
type that captures the syntax of expressions. Our expressions are simple
and do not have variables.

\begin{verbatim}


> data Expr = Const Double
>           | Plus  Expr Expr
>           | Minus Expr Expr
>           | Mul   Expr Expr
>           | Div   Expr Expr
\end{verbatim}
Now the evaluator is easy.

\begin{verbatim}

> eval :: Expr -> Double
> eval (Const d)      = d
> eval (Plus  a b)  = eval a + eval b
> eval (Minus a b)  = eval a - eval b
> eval (Mul   a b)  = eval a * eval b
> eval (Div   a b)  = eval a / eval b
\end{verbatim}
\section{The \texttt{Either} data type}

You might have noticed that that we do not handle the division by zero
errors So we want to capture functions that evaluates to a value or
returns an error. The Haskell library exports a data type called
\texttt{Either} which is useful in such a situation. For completeness,
we give the definition of \texttt{Either}. You can use the standard type
instead.

\begin{verbatim}

data Either a b = Left  a
                | Right b
\end{verbatim}
The data type \texttt{Either} is used in haskell often is situation
where a computation can go wrong like for example expression evaluation.
It has two constructors \texttt{Left} and \texttt{Right}. By convention
\texttt{Right} is used for the correct value and Left for the error
message: A way to remeber this convention is to remember that ``Right is
always right''.

We would want our evaluator to return either an error message or a
double. For convenience, we capture this type as \texttt{Result}.

\begin{verbatim}

> type Result a = Either String a
\end{verbatim}
The above expression is a \emph{type alias}. This means that
\texttt{Result a} is the same type as \texttt{Either String a}. As far
as the compiler is concerned, they are both same. We have already seen a
type aliasing in action namely \texttt{String} and \texttt{{[}Char{]}}.

We are now ready to define the new evaluator. We first give its type

\begin{verbatim}

> eval' :: Expr -> Result Double
\end{verbatim}
The definition of \texttt{eval'} is similar to eval for constructors
\texttt{Const}, \texttt{Plus}, \texttt{Minus} and \texttt{Mul} except
that it has to ensure.

\begin{enumerate}[1.]
\item
  Ensure each of the sub expressions have not resulted a division by
  zero error.
\item
  If the previous condition is met has to wrap the result into a
  \texttt{Result} data type using the \texttt{Right} constructor.
\end{enumerate}
Instead of explicit pattern matching we define a helper function for
this calle \texttt{app} that simplify this.

\begin{verbatim}

> zeroDivision = Left "Division by zero"

> app op (Right a)  (Right b) = Right (op a b)
> app _      _         _      = zeroDivision
\end{verbatim}
The constructor \texttt{Div} has to be handled seperately as it is the
only operator that generates an error. Again we write a helper here.

\begin{verbatim}

> divOp (Right a) (Right b) | b == 0     = zeroDivision
>                           | otherwise  = Right (a / b)
> divOp    _         _                   = zeroDivision -- problem any way.
\end{verbatim}
Now we are ready to define \texttt{eval'}.

\begin{verbatim}

> eval' (Const d)   = Right d
> eval' (Plus  a b) = app (+) (eval' a) (eval' b)
> eval' (Minus a b) = app (-) (eval' a) (eval' b)
> eval' (Mul   a b) = app (*) (eval' a) (eval' b)
> eval' (Div   a b) = divOp   (eval' a) (eval' b)
\end{verbatim}
Let us load the code in the interpreter

\begin{verbatim}

$ ghci src/lectures/An-expression-evaluator.lhs
GHCi, version 7.0.3: http://www.haskell.org/ghc/  :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer-gmp ... linking ... done.
Loading package base ... linking ... done.
Loading package ffi-1.0 ... linking ... done.
[1 of 1] Compiling Main             ( src/lectures/Expression.lhs, interpreted )
Ok, modules loaded: Main.
*Main> let [zero,one,two,three,four,five] = map Const [0..5]
*Main> eval' (Div five zero)
Left "Division by zero"
*Main> eval' (Plus (Div five zero) two)
Left "Division by zero"
*Main> eval' (Plus (Div five two) two)
Right 4.5
*Main>
\end{verbatim}

\end{document}
