<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">\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{array}
% This is needed because raggedright in table elements redefines \\:
\newcommand{\PreserveBackslash}[1]{\let\temp=\\#1\let\\=\temp}
\let\PBS=\PreserveBackslash
\usepackage{url}
\usepackage[breaklinks=true,unicode=true]{hyperref}
\setlength{\parindent}{0pt}
\setlength{\parskip}{6pt plus 2pt minus 1pt}
%\setcounter{secnumdepth}{0}

\title{Functional Programming Lecture notes}
\author{Piyush P Kurur}

\begin{document}
\maketitle

\chapter{Introduction}

In this course we will learn functional programming through haskell. The
main motivation of this course is to prepare people for real world
programming. To be a successful haskell programmer, I believe, one needs
the uncluttered thought of a mathematician combined with the pragmatism
of an Engineer. One can learn the basics in a matter of days. However,
one requires regular practice to be an accomplished programmer.

\section{What will be done in this course ?}

Covering the entire language, the mathematical background and the
libraries is impossible in a semester long course. So in the class we
will learn the basics of haskell and some of the mathematical notions.
In fact, most of the class will be devoted to understanding these
mathematical concepts. Programming in haskell is a good exercise to your
mathematical muscle and thus this is an important component of this
course. But I hope this course does not end up being a collection of
\href{http://en.wikipedia.org/wiki/Abstract\_nonsense}{abstract
nonsense}. Therefore, we will have regular (i.e.~weekly) \emph{ungraded}
assignments to pull us back to real world.

\section{Evaluation.}

Your grade will depend on your performance in exams (which constitutes
70\% of the marks) and in the semester long project (which takes up the
remaining 30\% of marks). There will be zero credit for the weekly
assignments. However, they are what will help you build the knowledge.

Projects can be done in a group of \emph{3 or less}. Beside the projects
have to be under version control and since it is expected to be in
haskell, should be released as a
\href{http://www.haskell.org/cabal}{cabal} package. I recommend using
\href{http://darcs.net}{darcs} as the version control program. We will
\textbf{NOT} discuss darcs or cabal in the course, you will have to
learn it on your own. You may choose on what you want to work on but I
will put up a list of sample projects for you to get an idea of the
scope of haskell as an application development framework.

Besides, I encourage you to use haskell in your other programming needs
like B.Tech project, M.Tech/Ph.D Thesis etc.

\setcounter{chapter}{1}

\chapter{Warming up}

We will start with the haskell interpreter \texttt{ghci}. To start the
interpreter type the following on the command line. You might see
something like this.

\begin{verbatim}
$ ghci
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.
Prelude&gt;
\end{verbatim}
The \texttt{Prelude\textgreater{}} is the prompt and the interpreter is
expecting you to type in stuff. What you can type is any valid haskell
expression. You can for example use ghci like a calculator.

\begin{verbatim}
Prelude&gt; 42
42
Prelude&gt; 2 + 4
6
Prelude&gt; sqrt 2
1.4142135623730951
\end{verbatim}
The line 5 \texttt{sqrt 2} is a \emph{function application}, the
function sqrt is applied on 2. In haskell, applying a function
\texttt{f} on an argument \texttt{x} is done by placing \texttt{f} on
the left of \texttt{x}. Function application associates to the left,
i.e. \texttt{f x y z} means \texttt{((f x) y)z}.

\section{Types}

Although it did not appear to be the case in this limited interaction,
Haskell is a strongly typed language unlike python or scheme. All values
in haskell have a type. However we can almost always skip types. This is
because the compiler/interpreter infers the correct type of the
expression for us. You can find the type of an expression prefixing it
with `:type' at the prompt. For example

\begin{verbatim}
Prelude&gt; :type 'a'
'a' :: Char
\end{verbatim}
In haskell the a type of a value is asserted by using \texttt{::} (two
colons). The interpreter just told us that \texttt{'a'} is an expression
of type \texttt{Char}.

Some basic types in Haskell are given in the table below

\ctable[pos = H, center, botcap]{ll}
{% notes
}
{% rows
\FL
Haskell type &amp; What they are
\ML
Bool &amp; Boolean type
\\\noalign{\medskip}
Int &amp; Fixed precision integer
\\\noalign{\medskip}
Char &amp; Character
\\\noalign{\medskip}
Integer &amp; Multi-precision integer
\LL
}

\section{Lists and Strings.}

A list is one of the most important data structure in Haskell. A list is
denoted by enclosing its components inside a square bracket.

\begin{verbatim}
Prelude&gt; :type ['a','b']
['a','b'] :: [Char]
Prelude&gt; :type "abcde"
"abcde" :: [Char]
\end{verbatim}
A string in Haskell is just a list of characters. The syntax of a string
is exactly as in say C with escapes etc. For example
\texttt{"Hello world"} is a string.

Unlike in other languages like python or scheme, a list in Haskell can
have only one type of element, i.e. \texttt{{[}1, 'a'{]}} is \emph{not}
a valid expression in haskell. A list of type \texttt{t} is denoted by
\texttt{{[}t{]}} in haskell. Example the type \texttt{String} and
\texttt{{[}Char{]}} are same and denote strings in Haskell.

\section{Functions.}

In haskell functions are first class citizens. They are like any other
values. Functions can take functions as arguments and return functions
as values. A function type is denoted using the arrow notation, i.e.~A
function that takes an integer and returns a character is denoted by
\texttt{Integer -\textgreater{} Char}.

\begin{verbatim}
Prelude&gt; :type length
length :: [a] -&gt; Int
\end{verbatim}
Notice that the interpreter tells us that length is a function that
takes the list of \texttt{a} and returns an \texttt{Int} (its length).
The type \texttt{a} in this context is a \emph{type variable}, i.e.~as
far as length is concerned it does not care what is the type of its
list, it returns the length of it. In Haskell one can write such generic
functions. This feature is called polymorphism. The compiler/interpreter
will appropriately infer the type depending on its arguments

\begin{verbatim}
Prelude&gt; length [1,2,3]
3
Prelude&gt; length "Hello"
5
\end{verbatim}
Polymorphism is one of the greatest strengths of Haskell. We will see
more of this in time to come.

Let us now define a simple haskell function.

\begin{verbatim}
fac 0 = 1
fac n = n * fac (n - 1)
\end{verbatim}
Save this in a file, say \texttt{fac.hs} and load it in the interpreter

\begin{verbatim}
$ ghci fac.hs
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             ( fac.hs, interpreted )
Ok, modules loaded: Main.
Main&gt; fac 0
1
Main&gt; fac 4
24
\end{verbatim}
A haskell function is defined by giving a set of equations. A function
equation looks like

\begin{verbatim}
f pat_1_1 pat_1_2 ... pat_1_n  = expr_1
f pat_2_1 pat_2_2 ... pat_2_n  = expr_2
          ...
f pat_m_1 pat_2_2 ... pat_m_n  = expr_m
\end{verbatim}
The formal parameters can be \emph{patterns}. We will define what
patterns in detail latter on but a constant like \texttt{0} or a
variable like \texttt{n} is a pattern. When a function is evaluated, its
actual arguments are \emph{matched} with each of the equations in turn.
We cannot explain what matching means in full detail here because we
have not explained patterns yet. However, for constant patterns like
\texttt{0} or a variable it is easy. An actual argument can match a
constant if and only if the argument evaluates to that constant. On the
other hand a variable pattern matches any argument. If a function
\texttt{f} is defined using $n$ equations, then while evaluating the
function on a set of arguments each equation is tried out in order. The
first equation of \texttt{f} whose formal parameters match the actual
argument is used for evaluation.

To illustrate we consider the function \texttt{fac} that we defined. The
expression \texttt{fac 0} evaluates to 1 because the actual parameter
matches with the formal parameter 0 in the first equation. On the other
hand, in the expression \texttt{fac 2} the actual argument \texttt{2}
cannot match the formal argument 0 in the first equation of
\texttt{fac}. Therefore the next equation is tried namely
\texttt{fac n = n * fac (n-1)}. Here the formal parameter \texttt{n}
matches 2 (recall a variable pattern can match any argument). Therefore,
\texttt{fac 2} evaluates to \texttt{2 * fac (2 - 1)} which by recursion
evaluates to 2.

We give two alternate defintions of the factorial function, the first
using \emph{guards} and the next using \texttt{if then else}.

\begin{verbatim}
fac1 n | n == 0      = 1
       | otherwise   = n * fac1 (n -1)

fac2 n = if n == 0 then 1 else n * fac2 (n -1)
\end{verbatim}
To summarise

\begin{enumerate}[1.]
\item
  Haskell functions are polymorphic
\item
  They can be recursive.
\item
  One can use pattern matching in their definition.
\end{enumerate}
\setcounter{chapter}{2}

\chapter{More on pattern matching.}

In the last lecture we, defined the factorial function and illustrated
the use of pattern matching. In this chapter we elaborate on it a bit
more.

\section{Pattern matching on lists.}

We have already seen the list type. There is an algebraic way of
defining a list. A list either an empty list or an element attached to
the front of an already constructed list. An empty list in Haskell is
expressed as \texttt{{[}{]}} where as a list whose first element is
\texttt{x} and the rest is \texttt{xs} is denoted by \texttt{x:xs}. The
notation \texttt{{[}1,2,3{]}} is just a
\emph{\href{http://en.wikipedia.org/wiki/Syntactic\_sugar}{syntactic
sugar}} for \texttt{1:(2:(3:{[}{]}))} or just \texttt{1:2:3:{[}{]}} as
\texttt{:} is a right associative operator. We now illustrate pattern
matching on list by giving the example of the \texttt{map} function. The
\texttt{map} function takes a function and a list and applies the
function on each element of the list. Here is the complete definition
including the type

\begin{verbatim}

&gt; import Prelude hiding (map, null, curry, uncurry)
&gt;        -- hide Prelude functions defined here
&gt;
&gt; map :: (a -&gt; b) -&gt; [a] -&gt; [b]
&gt; map f []           = []
&gt; map f (x:xs)       = f x : map f xs
\end{verbatim}
Since a list can either be empty or of the form \texttt{(x:xs)} this is
a complete definition. Also notice that pattern matching of variables is
done here.

\section{Literate programming detour.}

Before we proceed further, let us clarify the \texttt{\textgreater{}}'s
at the beginning of the of the lines. This is the
\href{http://en.wikipedia.org/wiki/Literate\_programming}{literate
programming} convention that Haskell supports.
\href{http://en.wikipedia.org/wiki/Literate\_programming}{Literate
programming} is a style of programming championed by
\href{http://www-cs-faculty.stanford.edu/\ensuremath{\sim}knuth}{Knuth},
where comments are given more importance than the code. It is not
restricted to Haskell alone; in fact \href{http://www.tug.org}{TeX} and
\href{http://en.wikipedia.org/wiki/METAFONT}{METAFONT} were written
first written by
\href{http://www-cs-faculty.stanford.edu/\ensuremath{\sim}knuth}{Knuth}
in a literate version Pascal language called
\href{http://en.wikipedia.org/wiki/WEB}{WEB} and later on ported to
\href{http://www-cs-faculty.stanford.edu/\ensuremath{\sim}knuth/cweb.html}{CWEB},
a literate version of the C Programming language. The \texttt{ghc}
compiler and the \texttt{ghci} interpreter supports both the literate
and non-literate version of Haskell.

Normally any line is treated as part of the program unless the
commented. In
\href{http://www.haskell.org/haskellwiki/Literate\_programming}{literate
haskell} all lines other than

\begin{enumerate}[1.]
\item
  Those that start with a `\textgreater{}' or
\item
  A block of lines enclosed in a \texttt{\textbackslash{}begin\{code\}}
  \texttt{\textbackslash{}end\{code\}}
\end{enumerate}
are treated as comments. We will use this literate style of programming;
we will use only the first form i.e.~program lines start with a
\texttt{\textgreater{}}. The advantage is that one can download the
notes directly and compile and execute them.

\section{Wild card patterns.}

We now illustrate the use of wild card patterns. Consider the function
that tests whether a list is empty. This can be defined as follows.

\begin{verbatim}

&gt; null [] = True
&gt; null _  = False
\end{verbatim}
The pattern \texttt{\_} (under score) matches any expression just like a
variable pattern. However, unlike a variable pattern where the matched
value is bound to the variable, a wild card discards the value. This can
be used when we do not care about the value in the RHS of the equation.

\section{Tuples and pattern matching.}

Besides lists Haskell supports the tuple type. Tuple types corresponds
to taking set theoretic products. For example the tuple
\texttt{(1,"Hello")} is an ordered pair consisting of the integer
\texttt{1} and the string \texttt{"Hello"}. Its type is
\texttt{(Int,String)} or equivalently \texttt{(Int,{[}Char{]})} as
\texttt{String} is nothing but \texttt{{[}Char{]}}. We illustrate the
pattern matching of tuples by giving the definition of the standard
functions \texttt{curry} and \texttt{uncurry}.

\section{A brief detour on currying}

In haskell functions are univariate functions unlike other languages.
Multi-parameter functions are captured using the process called
\emph{currying}. A function taking two arguments \texttt{a} and
\texttt{b} and returning \texttt{c} can be seen as a function taking the
\texttt{a} and returning a function that takes \texttt{b} and returning
\texttt{c}. This kind of function is called a \texttt{curried} function.
Another way in which we can represent a function taking 2 arguments is
to think of the function as taking a tuple. This is its uncurried form.
We now define the higher order functions that transforms between these
two forms.

\begin{verbatim}

&gt; curry    :: ((a,b) -&gt; c)  -&gt; a -&gt; b -&gt; c
&gt; uncurry  :: (a -&gt; b -&gt; c) -&gt; (a,b) -&gt; c
&gt;
&gt; curry   f a b   = f (a,b)
&gt; uncurry f (a,b) = f a b
\end{verbatim}
The above code clearly illustrates the power of Haskell when it comes to
manipulating functions. Use of higher order functions is one of the
features that we will find quite a bit of use.

\section{Summary}

In this lecture we saw

\begin{enumerate}[1.]
\item
  Pattern matching for lists,
\item
  Tuples and pattern matching on them,
\item
  Literate haskell
\item
  Higher order functions.
\end{enumerate}
\setcounter{chapter}{3}

\chapter{The Sieve of Eratosthenes.}

In this lecture, we look at an algorithm to find primes which you might
have learned in school. It is called the
\href{http://en.wikipedia.org/wiki/Sieve\_of\_Eratosthenes}{Sieve of
Eratosthenes}. The basic idea is the following.

\begin{enumerate}[1.]
\item
  Enumerate all positive integers starting from 2.
\item
  Forever do the following
\item
  Take the smallest of the remaining uncrossed integer say $p$ and
  circle it.
\item
  Cross out all numbers that are the factors of the circled integer $p$.
\end{enumerate}
All the circled integers are the list of primes. For an animated
description see the wiki link
\url{http://en.wikipedia.org/Sieve_of_Eratosthenes}.

We want to convert this algorithm to haskell code. Notices that the
Sieve seperates the primes from the composites. The primes are those
that are circled and composites are those that are crossed. So let us
start by defining

\begin{verbatim}

&gt; primes = circledIntegers
\end{verbatim}
i.e.~the primes are precisely the list of circled integers.

An integer gets circled if and only if it is not crossed at any stage of
the sieving process. Furthermore, a integer gets crossed in the stage
when its least prime factor is circled. So to check whether an integer
is crossed all we need to do is to check whether there is a prime which
divides it.

\begin{verbatim}

&gt; divides x n = n `mod` x == 0
&gt;
&gt; check (x:xs) n | x * x &gt; n      = True       -- the rest are bigger.
&gt;                | x `divides` n  = False      -- We hit a factor
&gt;                | otherwise      = check xs n -- need to do more work
&gt;
&gt; isCircled = check primes
&gt;
\end{verbatim}
The function \texttt{isCircle x} checks whether \texttt{x} will
eventually be circled. One need not go over all primes as the smallest
non-trivial prime $p$ that divides a composite number $n$ should always
be less than or equal to $\sqrt{n}$. This explains the first guard
statement of the check function.

\section{Guards detour.}

We now explain another feature of Haskell namely guards. Look at the
definition of the function \texttt{check}. Recall that a function is
defined by giving a set of equations. For each such equation, we can
have a set of guards. The syntax of these guarded equation looks like

\begin{verbatim}
f p_1 ... p_n | g_1  = e_1
              | g_2  = e_2
              | g_3  = e_3
              | ...
              | g_m  = e_m
\end{verbatim}
Each of the guards \texttt{g\_i} is a boolean expression. You should
read this as ``if \texttt{f}'s arguments match the patterns
\texttt{p1 ... pn} then its value is \texttt{e\_1} if \texttt{g\_1} is
true, \texttt{e\_2} if \texttt{g\_2} is true, etc \texttt{e\_m} if
\texttt{g\_m} is true''. If multiple guards are true then the guard
listed first has priority. For example consider the following function

\begin{verbatim}

&gt;
&gt; f x | x &gt;= 0 = "non-negative"
&gt;     | x &lt;= 0 = "negative"
\end{verbatim}
Then \texttt{f 0} is the string \texttt{"non-negative"}. If you want to
add a default guard, then use the keyword \texttt{otherwise}. The
keyword \texttt{otherwise} is nothing but the boolean value
\texttt{True}. However, in guards it is a convention to write
\texttt{otherwise} instead of \texttt{True}.

Finally, we want to define the list of \texttt{circledInteger}. Clearly
the first integer to be circled is 2. The rest are those integers on
which the function \texttt{isCircled} returns true. And here is the
Haskell code.

\begin{verbatim}

&gt;
&gt; circledIntegers = 2 : filter isCircled [3..]
&gt;
\end{verbatim}
Here filter is a function that does what you expect it to do. Its first
argument is a predicate, i.e it take an element and returns a boolean,
and its second argument is a list. It returns all those elements in the
list that satisfies the predicate. The type of filter is given by
\texttt{filter :: (a -\textgreater{} Bool) -\textgreater{} {[}a{]} -\textgreater{} {[}a{]}}.
This completes the program for sieving primes. Now load the program into
the interperter

\begin{verbatim}
$ ghci Sieve-of-Eratosthense.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/Sieve-of-Eratosthenes.lhs, interpreted )
Ok, modules loaded: Main.
*Main&gt; :type take
take :: Int -&gt; [a] -&gt; [a]
*Main&gt; take 10 primes
[2,3,5,7,11,13,17,19,23,29]
\end{verbatim}
The \texttt{take n xs} returns the first \texttt{n} elements of the list
\texttt{xs}.

\section{How is the circularity of primes handled?}

One thing you might have noticed is that the list \texttt{primes} has a
circular definition. The compiler is able to grok this circularity due
to the fact that Haskell is a lazy language. No expression is evaluated
unless it is required. For each integer in the list \texttt{primes} to
decide that it is circled, we need to consider only the primes that are
less than its square root. As a result the definition of primes does not
blow up into an infinitary computation.

\section{Infix application of function and prefix application of
operators.}

We now explain another feature of a Haskell. Notice the use of
\texttt{mod} in the expression n `mod` x == 0 in the definition of the
function \texttt{divides} and in the guard x `divides` n in the
definition of the function \texttt{check}. We have used a two argument
function (i.e.~its type is
\texttt{a -\textgreater{} b -\textgreater{} c}) like an operator. For
any such function \texttt{foo} we can convert it into a binary operator
by back quoting it, i.e. `foo`.

The converse is also possible, i.e.~we can convert an operator into the
corresponding function by enclosing it in a bracket. For example the
expression \texttt{(+)} (there is no space in side the bracket otherwise
it is an error) is a function
\texttt{Int -\textgreater{} Int -\textgreater{} Int}.

\begin{verbatim}

&gt; incr1 = map ((+) 1)
&gt; incr2 = map (+1)
\end{verbatim}
The two function \texttt{incr1} and \texttt{incr2} both does the same
thing; increments all the elements in a list of integers by 1.

\setcounter{chapter}{4}

\chapter{Fibonacci Series}

In continuation with the theme of the last lecture we define another
infinite series --- the fibonacci series. Ofcourse all of you know the
Fibonacci Series. It is defined by the linear recurrence relation
$F_{i+2} = F_i + F_{i+1}$. We assume that $F_0 = 1$ and $F_1 = 1$ to
begin with.

The defintion is straight forward; it is just a one liner, but we use
this as an excuse to introduce two standard list functions

\section{Ziping a list}

The zip of the list $x_0,...,x_n$ and $y_0,\ldots,y_m$ is the list of
tuples $(x_0,y_0),\ldots,(x_k,y_k)$ where $k$ is the minimum of $n$ and
$m$.

\begin{verbatim}

&gt; zip :: [a] -&gt; [b] -&gt; [(a,b)]
&gt; zip  []       _   = []
&gt; zip   _      []   = []
&gt; zip (x:xs) (y:ys) = (x,y) : zip xs ys
\end{verbatim}
The function \texttt{zipWith} is a general form of ziping which instead
of tupling combines the values with an input functions.

\begin{verbatim}

&gt; zipWith :: (a -&gt; b -&gt; c) -&gt; [a] -&gt; [b] -&gt; [c]
&gt; zipWith f xs ys = map (uncurry f) $ zip xs ys
\end{verbatim}
We can now give the code for fibonacci numbers.

\begin{verbatim}

&gt; fib = 1:1:zipWith (+) fib (tail fib)
\end{verbatim}
Notice that the zip of \texttt{fib} and \texttt{tail fib} gives a set of
tuples whose caluse are consecutive fibonacci numbers. Therefore, once
the intial values are set all that is required is zipping through with a
\texttt{(+)} operation.

\setcounter{chapter}{5}

\chapter{Folding Lists}

Will be up soon.

\setcounter{chapter}{6}

\chapter{Data types}

We have already seen an example of a compound data type namely list.
Recall that, a list is either an empty list or a list with a head
element and rest of the list. We begin by defining a list data type.
Haskell already provides a list data type so we do not need to define a
user defined data type. However, we do this for illustration

\begin{verbatim}

&gt; import Prelude hiding (sum) -- hide the standard sum function
&gt; data List a = EmptyList
&gt;             | Cons  a (List a)
\end{verbatim}
One reads this as follows ``List of \texttt{a} is either
\texttt{EmptyList} or a \texttt{Cons} of \texttt{a} and \texttt{List} of
\texttt{a}''. Here the variable \texttt{a} is a type variable. The
result of this is that \texttt{List} is now a polymorphic data type. We
can instatiate this with any other Haskell data types. A list of
integers is then \texttt{List Integer}.

The identifiers \texttt{EmptyList} and \texttt{Cons} are the two
\emph{constructors} of our new data type \texttt{List}. The constructors
can now be used in Haskell expressions. For example \texttt{EmptyList}
is a valid Haskell expression. So is \texttt{Cons 2 EmptyList} and
\texttt{Cons 1 (Cons 2 EmptyList)}. The standard list actually has two
constructors, namely \texttt{{[}{]}} and \texttt{(:)}.

\section{Pattern Matching}

We can now define functions on our new data type \texttt{List} using
pattern matching in the most obvious way. Here is a version of
\texttt{sum} that works with \texttt{List Int} instead of
\texttt{{[}Int{]}}

\begin{verbatim}

&gt; sum :: List Int -&gt; Int
&gt; sum EmptyList   = 0
&gt; sum (Cons x xs) = x + sum xs
\end{verbatim}
As the next example, we two functions to convert from our list type to
the standard list type.

\begin{verbatim}

&gt; toStdList   :: List a -&gt; [a]
&gt; fromStdList :: [a] -&gt; List a

&gt; toStdList EmptyList   = []
&gt; toStdList (Cons x xs) = x : toStdList xs

&gt; fromStdList []     = EmptyList
&gt; fromStdList (x:xs) = Cons x (fromStdList xs)
\end{verbatim}
\begin{enumerate}[1.]
\item
  \textbf{Exercise}: Define the functions \texttt{map} \texttt{foldr}
  and \texttt{foldl} for our new list type.
\end{enumerate}
\section{Syntax of a data type}

We now give the general syntax for defining data types.

\begin{verbatim}

data Typename tv_1 tv_2 tv_n = C1 te_11 te_12 ... te_1r1
                             | C2 te_21 te_22 ... te_2r2
                             |     . . .
                             | Cm te_m1 te_m2 ... te_mrm
\end{verbatim}
Here data is a key word that tells the complier that the next equation
is a data type definition. This gives a polymorphic data type with $n$
\emph{type arguments} \texttt{tv\_1,...,tv\_n}. The \texttt{te\_ij}'s
are arbitrary type expressions and the identifiers \texttt{C1} to
\texttt{Cm} are the constructors of the type. Recall that in Haskell
there is a constraint that each variable, or for that matter type
variable, \emph{should} be an identifer which starts with a lower case
alphabet. In the case of type names and constructors, they \emph{should}
start with upper case alphabet.

\section{Constructors}

Constructors of a data type play a dual role. In expressions they behave
like functions. For example in the \texttt{List} data type that we
defined the \texttt{EmptyList} constructor is a constant List (which is
the same as 0-argument function) and \texttt{Cons} has type
\texttt{a -\textgreater{} List a -\textgreater{} List a}. On the other
hand constructors can be used in pattern matching when defining
functions.

\section{The Binary tree}

We now look at another example the binary tree. Recall that a binary
tree is either an empty tree or has root and two children. In haskell
this can be captured as follows

\begin{verbatim}

&gt;
&gt; data Tree a = EmptyTree
&gt;             | Node (Tree a) a (Tree a)
&gt;
\end{verbatim}
To illustrate function on tree let us define the \texttt{depth} function

\begin{verbatim}

&gt; depth :: Tree a -&gt; Int
&gt; depth EmptyTree           = 0
&gt; depth (Node left _ right) | dLeft &lt;= dRight = dRight + 1
&gt;                           | otherwise       = dLeft  + 1
&gt;       where dLeft  = depth left
&gt;             dRight = depth right
\end{verbatim}
\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}


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

\begin{verbatim}

&gt; eval :: Expr -&gt; Double
&gt; eval (Const d)      = d
&gt; eval (Plus  a b)  = eval a + eval b
&gt; eval (Minus a b)  = eval a - eval b
&gt; eval (Mul   a b)  = eval a * eval b
&gt; 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}

&gt; 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}

&gt; eval' :: Expr -&gt; 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}

&gt; zeroDivision = Left "Division by zero"

&gt; app op (Right a)  (Right b) = Right (op a b)
&gt; 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}

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

\begin{verbatim}

&gt; eval' (Const d)   = Right d
&gt; eval' (Plus  a b) = app (+) (eval' a) (eval' b)
&gt; eval' (Minus a b) = app (-) (eval' a) (eval' b)
&gt; eval' (Mul   a b) = app (*) (eval' a) (eval' b)
&gt; 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&gt; let [zero,one,two,three,four,five] = map Const [0..5]
*Main&gt; eval' (Div five zero)
Left "Division by zero"
*Main&gt; eval' (Plus (Div five zero) two)
Left "Division by zero"
*Main&gt; eval' (Plus (Div five two) two)
Right 4.5
*Main&gt;
\end{verbatim}
\setcounter{chapter}{8}

\chapter{Lambda Calculus}

We now look at lambda calculus, the theoretical stuff that underlies
functional programming. It was introduced by Alonzo Church to formalise
two key concepts when dealing with functions in mathematics and logic
namely: function definition and function application. In this lecture,
we build enough stuff to get a lambda calculus evaluator.

\begin{verbatim}

&gt; module Lambda where
&gt; import Data.List -- I need some standard list functions
\end{verbatim}
We start with an example. Consider the squaring function, i.e.~the
function that maps $x$ to $x^2$. In the notation of lambda calculus this
is denoted as $\lambda x . x^2$. This is called a lambda abstraction.
Apply a function $f$ on an expression $N$ is written as $f N$. The key
rule in expression evaluation is the $\beta$-reduction: the expression
$(\lambda x. M) N$ reduces under $\beta$-reduction to the expression $M$
with $N$ substituted in it. We now look at lambda calculus formally.

The goal of this lecture is to introduce basics of lambda calculus and
on the way implement a small lambda calculus interpreter.

\section{Abstract syntax}

As with any other formal system we first define its abstract syntax. A
lambda calculus expression is defined via the grammar

\[ e := v | e_1 e_2 | \lambda x . e \]

Here $e_1$ and $e_2$ expressions themselves. We now capture this
abstract syntax as a Haskell data type

\begin{verbatim}

&gt; -- | The datatype that captures the lambda calculus expressions.
&gt; data Expr = V    String       -- ^ A variable
&gt;           | A    Expr   Expr  -- ^ functional application
&gt;           | L    String Expr  -- ^ lambda abstraction
&gt;           deriving Show
\end{verbatim}
\section{Free and bound variables}

The notion of free and bound variables are fundamental to whole of
mathematics. For example in the integral $\int \sin{xy} dy$, the
variable $x$ occurs \emph{free} where as the variables $y$ occurs
\emph{bound} (to the corresponding $\int dy$). Clearly the value of the
expression does \emph{not} depend on the bound variable; in fact we can
write the same integral as $\int \sin{xt} dt$.

In lambda calculus we say a variable occurs bound if it can be linked to
a lambda abstraction. For example in the expression $\lambda x. xy$ the
variable $x$ is bound where as $y$ occurs free. A variable can occur
free as well as bound in an expression --- consider $x$ in
$\lambda y. x (\lambda x.x)$.

Formally we can define the free variables of a lambda expression as
follows.

\[FV (v)            = \{ v\}\]
\[FV(e_1 e_2)       = FV(e_1) \cup FV(e_2)\]
\[FV (\lambda x. e) = FV(e) \setminus \{ x \}\]

We turn this into haskell code

\begin{verbatim}

&gt; freeVar :: Expr -&gt; [String]
&gt; freeVar (V x  ) = [x]
&gt; freeVar (A f e) = freeVar f `union` freeVar e
&gt; freeVar (L x e) = delete x $ freeVar e
\end{verbatim}
\section{Variable substitution}

We often need to substitute variables with other expressions. Since it
is so frequent we give a notation for this. By $M [ x := e]$, we mean
the expression obtained by replacing all free occurrence of $x$ in $M$
by $e$. Let us code this up in haskell.

\begin{verbatim}

&gt; subst :: Expr -&gt; String -&gt; Expr -&gt; Expr
&gt; subst var@(V y)   x e | y == x    = e
&gt;                       | otherwise = var
&gt; subst (A f a) x e                 = A (subst f x e) (subst a x e)
&gt; subst lam@(L y a) x e | y == x    = lam
&gt;                       | otherwise = L y (subst a x e)
\end{verbatim}
\section{Change of bound variables ($\alpha$-reduction)}

You are already familiar with this in mathematics. If we have an
integral of the kind $\int x t dt$ we can rewrite it as $\int x y dy$ by
a change of variable. The same is true for lambda calculus. We say call
the ``reduction'' $\lambda x .M \leftarrow \lambda t. M [x :=t]$ as the
$\alpha$-reduction. However care should be taken when the new variable
is chosen. Two pitfalls to avoid when performing $\alpha$-reduction of
the expression $\lambda x. M$ to $\lambda t. M[x := t]$ is

\begin{enumerate}[1.]
\item
  The variable $t$ should not be free in $M$ for otherwise by changing
  from $x$ to $t$ we have bound an otherwise free variable. For example
  if $M=t$ then $\lambda t. M[x=t]$ becomes $\lambda t.t$ which is
  clearly wrong.
\item
  If $M$ has a free occurrence of $x$ in the scope of a bound occurrence
  of $t$ then we cannot perform change the bound variable $x$ to $t$.
  For example consider $M = \lambda t. x t$. Then $\lambda t. M[x=t]$
  will become $\lambda t. \lambda t. t t$ which is clearly wrong.
\end{enumerate}
Clearly, one safe way to do $\alpha$-reduction on $\lambda x. M$ is to
use a fresh variable $t$, i.e.~a variable that is neither free nor bound
in $M$. We write a helper function to compute all the variables of a
lambda calculus expression.

\begin{verbatim}

&gt; varsOf :: Expr -&gt; [String]
&gt; varsOf (V x)   = [x]
&gt; varsOf (A f e) = varsOf f `union` varsOf e
&gt; varsOf (L x e) = varsOf e `union` [x]
\end{verbatim}
We now give the code to perform a safe change of bound variables.

\begin{verbatim}

&gt; alpha :: Expr -&gt; [String] -&gt; Expr
&gt; alpha (A f e) vars                     = A (alpha f vars) (alpha e vars)
&gt; alpha (L x e) vars | x `elem` vars     = L t $ alpha e' vars
&gt;                    | otherwise         = L x $ alpha e  vars
&gt;       where t  = fresh (varsOf e `union` vars)
&gt;             e' = subst e x (V t)
&gt; alpha  e       _                       = e
\end{verbatim}
\section{Function evaluation ($\beta$-reduction)}

The way lambda calculus captures computation is through $\beta$
reduction. We already saw what is $\beta$ reduction. Under beta
reduction, an expression $(\lambda x . M) N$ reduces to $M [x := N]$,
where $M[x:=N]$ denotes substitution of \emph{free} occurrences of $x$
by $N$. However, there is a chance that a free variable of $N$ could
become bound suddenly. For example consider $N$ to be just $y$ and $M$
to be $\lambda y. x y$. Then reducing $(\lambda x . M) N$ to $M[x := N]$
will bind the free variable $y$ in $N$.

We now give the code for $\beta$ reduction. It performs one step of beta
reduction that too if and only if the expression is of the form
$(\lambda x . M) N$.

\begin{verbatim}

&gt; beta :: Expr -&gt; Expr
&gt; beta (A (L x m) n) = carefulSubst m x n
&gt; carefulSubst m x n = subst (alpha m $ freeVar n) x n
&gt; 
\end{verbatim}
\section{Generating Fresh variables}

We saw that for our evaluator we needed a source of fresh variables. Our
function fresh is given a set of variables and its task is to compute a
variable name that does not belong to the list. We use diagonalisation,
a trick first used by Cantor to prove that Real numbers are of strictly
higher cardinality than integers.

\begin{verbatim}

&gt; fresh :: [String] -&gt; String
&gt; fresh = foldl diagonalise "a"
&gt;
&gt; diagonalise  []        []               = "a" -- diagonalised any way
&gt; diagonalise  []      (y:ys) | y == 'a'  = "b" -- diagonalise on this character
&gt;                             | otherwise = "a" 
&gt; diagonalise  s        []                =  s  -- anyway s is differnt from t
&gt; diagonalise s@(x:xs) (y:ys) | x /= y    = s   -- differs at this position anyway
&gt;                             | otherwise = x : diagonalise xs ys
&gt;
\end{verbatim}
\section{Exercise}

\begin{enumerate}[1.]
\item
  Read up about
  \href{http://en.wikipedia.org/wiki/Beta\_normal\_form}{$\beta$-normal}
  forms. Write a function that converts a lambda calculus expression to
  its normal form if it exists. There are different evaluation
  strategies to get to $\beta$-normal form. Code them all up.
\item
  The use of \texttt{varOf} in $\alpha$-reduction is an overkill. See if
  it can be improved.
\item
  Read about $\eta$-reduction and write code for it.
\end{enumerate}
\setcounter{chapter}{9}

\chapter{Modules}

Will be up soon.

\setcounter{chapter}{10}

\chapter{Towards type inference}

A powerful feature of Haskell is the automatic type inference of
expressions. In the next few lectures, we will attempt to give an idea
of how the type inference algorithm works. Ofcourse giving the type
inference algorithm for the entire Haskell language is beyond the scope
of this lecture so we take a toy example. Our aim is to give a complete
type inference algorithm for an enriched version of lambda calculus,
that has facilities to do integer arithmetic. Therefore, our lambda
calulus expressions have, besides the other stuff we have seen, integer
constants and the built in function `+'. We limit ourselves to only one
operator because it is straight forward to extend our algorithm to work
with other operation

\section{Syntax of our Enriched Lambda calculus.}

The syntax is given below. Here $v$ and $x$ stands for arbitrary
variable and $e_1$,$e_2$ stands for arbitrary expressions.

\[ e = ... | -1 | 0 | 1 | ... | + | v |e_1 e_2 | \lambda x . e \]

We will write the lambda calculus expression $+ e1 e2$ in its infix form
$e1 + e2$ for ease of readability.

The haskell datatype that captures our enriched lambda calculus
expression is the following

\begin{verbatim}

&gt; module Lambda where
&gt;
&gt; -- | The enriched lambda calculus expression.
&gt; data Expr = C Integer      -- ^ A constant
&gt;           | P              -- ^ The plus operator
&gt;           | V String       -- ^ The variable
&gt;           | A Expr Expr    -- ^ function application
&gt;           | L String Expr  -- ^ lambda abstraction
&gt;       deriving (Show, Eq, Ord)
\end{verbatim}
Clearly stuff like \texttt{A (C 2) (C 3)} are invalid expressions but we
ignore this for time being. One thing that the type checker can do for
us is to catch such stuff.

\section{Types}

We now want to assign types to the enriched lambda calculus that we
have. As far as we are concerned the types for us are

\[ t = \mathbf{Z} | \alpha | t_1 \to t_2 \]

Here $\alpha$ is an arbitrary type variable. Again, we capture it in a
Haskell datatype.

\begin{verbatim}

&gt; data Type = INTEGER
&gt;           | TV String
&gt;           | TA Type Type deriving (Show, Eq, Ord)
\end{verbatim}
\section{Conventions}

We will follow the following convention when dealing with type
inference. The lambda calculus expressions will be denoted by Latin
letters $e$, $f$, $g$ etc with appropriate subscripts. We will reserve
the Latin letters $x$, $y$, $z$ and $t$ for lambda calculus variables.
Types will be represented by the Greek letter $\tau$ and $\sigma$ with
the letters $\alpha$ and $\beta$ reserved for type variables.

\section{Type specialisation}

The notion of type specialisation is intuitivly clear. The type
$\alpha \to \beta$ is a more general type than $\alpha \to \alpha$. We
use $\sigma \leq \tau$ to denote the fact that $\sigma$ is
specialisation of $\tau$. How do we formalise this notion of
specialisation ? Firstly note that any constant type like for example
integer cannot be specialised further. Secondly notice that a variable
$\alpha$ can be specialised to a type $\tau$ as long as $\tau$ does not
have an occurance of $\alpha$ in it. We will denote a variable
specialisation by $\alpha \leftarrow \tau$. When we have a set of
variable specialisation we have to ensure that there is no cyclicity
indirectly. We doe this as follows. We say a sequence
$\Sigma = \{ \alpha_1 \leftarrow \tau_1,\ldots, \alpha_n \leftarrow \tau_n \}$
is a consistent set of specialisation if for each $i$, $\tau_i$ does not
contain any of the variables $\alpha_j$, $1\leq j \leq i$. Now we can
define what a specialisation is. Given a consistent sequence of
specialisation $\Sigma$ let $\tau[\Sigma]$ denote the type obtained by
substituting for variables in $\tau$ with their specialisations in
$\Sigma$. Then we say that $\sigma \leq \tau$ if there is a
specialisation $\Sigma$ such that $\tau[\Sigma] = \sigma$. The
specialisation order gives a way to compare two types. It is not a
partial order but can be converted to one by appropriate quotienting. We
say two types $\tau$ $\sigma$ are isomorphic, denoted by
$\sigma \equiv \tau$ if $\sigma \leq \tau$ and $\tau \leq \sigma$. It
can be shown that $\equiv$ forms an equivalence relation on types. Let
$\lceil{\tau}\rceil$ denote the equivalence class associated with $\tau$
then, it can be show that $\leq$ is a partial order on
$\left\lceil{\tau}\right\rceil$.

\section{Type environment}

Recall that the value of a \emph{closed} lambda calculus expression,
i.e.~a lambda calculus expression with no free variables, is completely
determined. More generally, given an expression $M$, its value depends
only on the free variables in it. Similary the type of an expression $M$
is completely specified once all its free variables are assigned types.
A \emph{type environment} is an assignment of types to variables. So the
general task is to infer the type of a lambda calculus expression $M$ in
a given type environment $\Gamma$ where all the free varaibles of $M$
have been assigned types. We will denote the type environments with with
capital Greek letter $\Gamma$ with appropriate subscripts if required.
Some notations that we use is the following.

\begin{enumerate}[1.]
\item
  We write $x :: \tau$ to denote that the variable $x$ has been assigned
  the type $\tau$.
\item
  For a variable $x$, we use $\Gamma(x)$ to denote the type that the
  type environment $\Gamma$ assigns to $x$.
\item
  We write $x \in \Gamma$ if $\Gamma$ assigned a type for the variable
  $x$.
\item
  The type environment $\Gamma_1 \cup \Gamma_2$ denotes the the type
  environment $\Gamma$ such that $\Gamma(x) = \Gamma_2(x)$ if
  $x \in \Gamma_2$ and $\Gamma_1(x)$ otherwise, i.e.~the second type
  environment has a precedence.
\end{enumerate}
As we described before, given a type environment $\Gamma$, the types of
any lambda calculus expression whose free variables are assigned types
in $\Gamma$ can be infered. We use the notation
$\Gamma \vdash e :: \tau$ to say that under the type environment
$\Gamma$ one can infer the type $\tau$ for $e$.

The type inference is like theorem proving: Think of infering $e:: \tau$
as proving that the expression $e$ has type $\tau$. Such an inference
requires a set of rules which for us will be the type inference rules.
We express this inference rules in the following notation

\[ \frac{\textrm{Premise 1},\ldots, \textrm{Premise
n}}{\textrm{conclusion}} \]

The type inference rules that we have are the following

Rule \emph{Const} : \[ \frac{}{\Gamma \vdash n :: \mathbf{Z}}\] where
$n$ is an arbitrary integer.

Rule \emph{Plus} :
\[\frac{}{\Gamma \vdash + :: \mathbf{Z} \to \mathbf{Z} \to \mathbf{Z} }\]

Rule \emph{Var} :
\[ \frac{}{\Gamma \cup \{ x :: \tau\} \vdash x :: \tau}\]

Rule \emph{Apply} :
\[ \frac{\Gamma \vdash f :: \sigma \to \tau,\ \ \Gamma \vdash e :: \sigma}
               {\Gamma \vdash f e :: \tau}\]

Rule \emph{Lambda} :
\[ \frac{\Gamma \cup \{x :: \sigma\} \vdash e :: \tau}
          {\Gamma \vdash \lambda x . e :: \sigma \to \tau}\]

Rule \emph{Specialise} :
\[\frac{\Gamma \vdash e :: \tau, \sigma \leq \tau}{\Gamma \vdash e
     :: \sigma}\]

The goal of the type inference algorithm is to infer the most general
type, i.e.~Given an type environment $\Gamma$ and an expression $e$ find
the type $\tau$ that satisfies the following two conditions

\begin{enumerate}[1.]
\item
  $\Gamma \vdash e :: \tau$ and,
\item
  If $\Gamma \vdash e :: \sigma$ then $\sigma \leq \tau$.
\end{enumerate}
\section{Exercises}

\begin{enumerate}[1.]
\item
  A pre-order is a relation that is both reflexive and transitive.
  \begin{itemize}
  \item
    Show that the specialisation order $\leq$ defined on types is a
    pre-order.
  \item
    Given any pre-oder $\preceq$ define the associated relation $\simeq$
    as $a \simeq b$ if $a \preceq b$ and $b \preceq a$. Prove that
    $\simeq$ is an equivalence class. Show that $\preceq$ can be
    converted into a natural partial order on the equivalence class of
    $\simeq$.
  \end{itemize}
\item
  Prove that if $\sigma$ and $\tau$ are two types such that
  $\sigma \equiv \tau$ then prove that there is a bijection between the
  set $Var(\sigma)$ and $Var(\tau)$ given by $\alpha_i \mapsto \beta_i$
  such that $\sigma[\Sigma] = \tau$ where $\Sigma$ is a specialisation
  $\{\alpha_i \leftarrow \beta_i | 1 \leq i \leq n\}$. In particular
  isomorphic types have same number of variables. (Hint: use induction
  on the number of variables that occur in $\sigma$ and $\tau$).
\end{enumerate}
\setcounter{chapter}{11}

\chapter{Unification algorithm}

On of the key steps involved in type inference is the unification
algorithm. Given two type $\tau_1$ and $\tau_2$ a \emph{unifier} if it
exists is a type $\tau$ such that $\tau$ is a specialisation of both
$\tau_1$ and $\tau_2$. The \emph{most general unifier} of $\tau_1$ and
$\tau_2$, if it exists, is the unifier which is most general, i.e.~it is
the unifier $\tau^*$ of $\tau_1$ and $\tau_2$ such that all other
unifiers $\tau$ is a specialisation of $\tau^*$. In this lecture we
develop an algorithm to compute the most general unifier of two types
$\tau_1$ and $\tau_2$.

\begin{verbatim}

&gt; {- | Module defining the unification algorithm -}
&gt;
&gt; module Unification where
&gt; import Lambda                  -- See the last lecture 
&gt; import qualified Data.Map as M -- To define specialisation.
&gt; import Data.Either
&gt; import Data.Maybe
&gt;
&gt; type Map = M.Map
\end{verbatim}
Although we defined the unifier as a type, it is convenient when
computing the unifier of $\tau_1$ and $\tau_2$ to compute the type
specialisation $\Sigma$ that unifies them to their most general unifier.
We will therefore abuse the term most general unifier to also mean this
specialisation. Also for simplicity we drop the adjective ``most
general'' and just use unifier to mean the most general unifier.

\begin{verbatim}

&gt; type Specialisation = Map String Type -- ^ A type specialisation
&gt; type Result         = Either String   -- ^ The error message if it failed
&gt;                      Specialisation   -- ^ The unifier
&gt;
&gt; unify               :: Type -&gt; Type -&gt; Result
\end{verbatim}
A type specialisation is captured by a \texttt{Map} from type variable
names to the corresponding specialisation. We given an function to
compute $\tau[\Sigma]$ given a specialisation $\Sigma$.

\begin{verbatim}

&gt; specialise :: Specialisation -&gt; Type -&gt; Type 
&gt; specialise sp t@(TV x) = maybe t (specialise sp) $ M.lookup x sp
&gt; specialise sp (TA s t) = TA (specialise sp s) (specialise sp t)
&gt; specialise sp  i       = i 
\end{verbatim}
We generalise the unification in two ways:

\begin{enumerate}[1.]
\item
  We consider unification of types under a particular specialisation
  $\Sigma$. The unifier of $\tau_1$ and $\tau_2$ \emph{under the
  specialisation} $\Sigma$ is nothing but the unifier of
  $\tau_1[\Sigma]$ and $\tau_2[\Sigma]$. The unification of two types
  can then be seen as unification under empty specialisation.
\end{enumerate}
\begin{verbatim}

&gt; genUnify  :: Specialisation -&gt; Type -&gt; Type -&gt; Result
&gt; unify     = genUnify M.empty
\end{verbatim}
\begin{enumerate}[1.]
\setcounter{enumi}{1}
\item
  Instead of considering unifiers of pairs of types $\tau_1$ and
  $\tau_2$, we consider the simultaneous unifier of a sequence of pairs
  $\{ (\tau_1,\sigma_1), \ldots, (\tau_n,\sigma_n) \}$. A unifier of
  such a sequence is a specialisation $\Sigma$ such that
  $\tau_i[\Sigma] = \sigma_i[\Sigma]$ for all $1 \leq i \leq n$. Of
  course we want to find the most general of such unifier. We call this
  function \texttt{genUnify'}. Given, \texttt{genUnify} it is easy to
  define \texttt{genUnify'}.
\end{enumerate}
\begin{verbatim}

&gt; genUnify'  :: Specialisation  -- ^ pair of types to unify
&gt;            -&gt; [(Type,Type)]   -- ^ the specialisation to unify under
&gt;            -&gt; Result          -- ^ the resulting unifier
&gt; genUnify' = foldl fld . Right
&gt;           where fld (Right sp) (tau,sigma) = genUnify sp tau sigma
&gt;                 fld err            _       = err
\end{verbatim}
What is left is the definition of \texttt{genUnify}.

\begin{verbatim}

&gt; genUnify sp (TV x)   t       = unifyV sp x t
&gt; genUnify sp t        (TV x)  = unifyV sp x t
&gt; genUnify sp INTEGER  t       = unifyI sp t
&gt; genUnify sp t        INTEGER = unifyI sp t
&gt; genUnify sp ap1      ap2     = unifyA sp ap1 ap2
&gt;
\end{verbatim}
The order of the pattern matches are important. For example notice that
in line 6, both \texttt{ap1} and \texttt{ap2} have to be an arrow type
(why?) Also in lines 3 and 4, t can either be \texttt{INTEGER} or an
arrow type.

So our rules of unification can are split into unifying a variable
$\alpha$ with a type $\tau$, a constant types (here Integer) with a type
$\tau$ and unifying two arrow types. We capture these rules with
functions \texttt{unifyV}, \texttt{unifyI} and \texttt{unifyA}
respectively.

\begin{verbatim}

&gt; unifyV :: Specialisation -&gt; String -&gt; Type -&gt; Result
&gt; unifyI :: Specialisation -&gt; Type   -&gt; Result
&gt; unifyA :: Specialisation -&gt; Type   -&gt; Type -&gt; Result
\end{verbatim}
\section{Unifying a variable and a type}

Unification of variables can be tricky since specialisations are
involved. Firstly, notice that if $\alpha$ occurs in a type $\tau$, we
cannot unify $\alpha$ with $\tau$ unless $\tau$ is $\alpha$ itself. We
first give a function to check this.

\begin{verbatim}

&gt; occurs :: Specialisation -&gt; String -&gt; Type -&gt; Bool
&gt; occurs sp x (TV y)   | x == y    = True
&gt;                      | otherwise = maybe False (occurs sp x) $ M.lookup y sp
&gt; occurs sp x (TA s t) = occurs sp x s || occurs sp x t
&gt; occurs sp x  _       = False
\end{verbatim}
The rules of unification of a variable $\alpha$ and a type $\tau$ are
thus

\begin{enumerate}[1.]
\item
  If $\alpha$ has a specialisation $\sigma$, unify $\sigma$ and tau,
\item
  If $\tau$ is $\alpha$ or can be specialised to $\alpha$ then we
  already have the specialisation.
\item
  If $\alpha$ is unspecialised then specialise it with $\tau$ provided
  there occurs no recursion either directly or indirectly.
\end{enumerate}
\begin{verbatim}

&gt; unifyV  sp x t = maybe (unifyV' sp x t) (genUnify sp t) $ M.lookup x sp
&gt;
&gt; unifyV' sp x INTEGER                 = Right $ M.insert x INTEGER sp
&gt; unifyV' sp x var@(TV y)  | x == y    = Right $ sp
&gt;                          | otherwise = maybe (Right $ M.insert x var sp)
&gt;                                              (unifyV' sp x)
&gt;                                              $ M.lookup y sp
&gt; unifyV' sp x ap@(TA s t) | occurs sp x s = failV sp x ap
&gt;                          | occurs sp x t = failV sp x ap
&gt;                          | otherwise  = Right $ M.insert x ap sp
&gt;
&gt; failV sp x ap = Left $ unwords [ "Fail to unify", x, "with" , ppSp sp ap
&gt;                                , ": recursion detected."
&gt;                                ]
&gt;                                          
\end{verbatim}
Notice here that \texttt{M.lookup x sp} returns \texttt{Nothing} if
\texttt{x} is not specialised under the specialisation \texttt{sp}. The
function $unifyV'$ unifies only an unspecialised variable with $\tau$.

\section{Unifying an integer and type}

Notice here that the type $\tau$ is not a variable. Then it can only be
Integer or an arrow type.

\begin{verbatim}

&gt; unifyI sp INTEGER = Right sp
&gt; unifyI sp t       = Left $ unwords [ "Failed to unify Integer with type"
&gt;                                    , ppSp sp t
&gt;                                    ]
\end{verbatim}
\section{Unifying two arrow types}

\begin{verbatim}

&gt; unifyA sp ap1@(TA a b) ap2@(TA c d) = either errmsg Right
&gt;                                     $ genUnify' sp [(a,c),(b,d)]
&gt;          where errmsg str = Left $ unwords [ "while unifying"
&gt;                                            , ppSp sp ap1, "and"
&gt;                                            , ppSp sp ap2
&gt;                                            ] ++ "\n" ++ str
\end{verbatim}
\section{Helper functions.}

We now document the helper functions used in the unification algorithm.
First we give an algorithm to \emph{pretty print} types. This makes our
error messages more readable. Notice that this version does not put
unnecessary brackets.

\begin{verbatim}

&gt; -- | Pretty print a type
&gt;
&gt; pp :: Type -&gt; String
&gt; pp INTEGER  = "Integer"
&gt; pp (TV x)   = x
&gt; pp (TA s t) = bracket s ++ " -&gt; " ++ pp t
&gt;        where bracket t@(TA r s) = "(" ++ pp t ++ ")"
&gt;              bracket s          = pp s 
&gt;
&gt; -- | Pretty print a specialised type
&gt; ppSp :: Specialisation -&gt; Type -&gt; String
&gt; ppSp sp = pp . specialise sp

\end{verbatim}
\section{Testing this code using ghci}

Since the lecture used the module of the previous lecture you need to
give the following commandline arguments.

\begin{verbatim}

$ ghci src/lectures/Unification-algorithm.lhs src/lectures/Towards-type-inference.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 2] Compiling Lambda           ( src/lectures/Towards-type-inference.lhs, interpreted )
[2 of 2] Compiling Unification      ( src/lectures/Unification-algorithm.lhs, interpreted )
Ok, modules loaded: Unification, Lambda.
*Unification&gt; let [a,b,c,d,e] = map TV $ words "a b c d e"
*Unification&gt; unify (TA INTEGER a) b
Loading package array-0.3.0.2 ... linking ... done.
Loading package containers-0.4.0.0 ... linking ... done.
Right (fromList [("b",TA INTEGER (TV "a"))])
*Unification&gt; unify (TA INTEGER a) (TA b (TA b c))
Right (fromList [("a",TA (TV "b") (TV "c")),("b",INTEGER)])
*Unification&gt;
*Unification&gt; let t = (TA a b)
*Unification&gt; unify (TA INTEGER a) (TA c t)
Left "while unifying Integer -&gt; a and c -&gt; a -&gt; b\nFail to unify a with a -&gt; b : recursion detected."
*Unification&gt; let Left l = unify (TA INTEGER a) (TA c t)
*Unification&gt; putStrLn l
while unifying Integer -&gt; a and c -&gt; a -&gt; b
Fail to unify a with a -&gt; b : recursion detected.
*Unification&gt;
\end{verbatim}
\setcounter{chapter}{12}

\chapter{The type inference algorithm}

Will be up some day.

\setcounter{chapter}{13}

\chapter{Type classes}

Consider the following interaction with the \texttt{ghci}

\begin{verbatim}

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.
Prelude&gt; (+) 1

&lt;interactive&gt;:1:1:
    No instance for (Show (a0 -&gt; a0))
      arising from a use of `print'
    Possible fix: add an instance declaration for (Show (a0 -&gt; a0))
    In a stmt of an interactive GHCi command: print it
Prelude&gt; (+) 1 2
3
Prelude&gt;
\end{verbatim}
Here the interpreter is able to display the value \texttt{3} but not the
function \texttt{(+) 1}. The error message is instructive. It says that
there is no instance of \texttt{Show (a0 -\textgreater{} a0)} for use
with \texttt{print}. Let us see what \texttt{Show} and \texttt{print}
are by using the \texttt{:info} command of the interpreter.

\begin{verbatim}
$ ghci
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.
Prelude&gt; :info Show
class Show a where
  showsPrec :: Int -&gt; a -&gt; ShowS
  show :: a -&gt; String
  showList :: [a] -&gt; ShowS
        -- Defined in GHC.Show
instance (Show a, Show b) =&gt; Show (Either a b)
  -- Defined in Data.Either
instance Show a =&gt; Show [a] -- Defined in GHC.Show
instance Show Ordering -- Defined in GHC.Show
instance Show a =&gt; Show (Maybe a) -- Defined in GHC.Show
instance Show Int -- Defined in GHC.Show
instance Show Char -- Defined in GHC.Show
instance Show Bool -- Defined in GHC.Show

[lots of similar lines delete]

Prelude&gt; :info print
print :: Show a =&gt; a -&gt; IO ()   -- Defined in System.IO
Prelude&gt;
\end{verbatim}
To understand what it means we need to know how the interpreter behaves.
When even you enter an expression on the command line the interpreter
evaluates and tries to print it. However not all haskell types are
printable. The function \texttt{print} has the type
\texttt{Show a =\textgreater{} a -\textgreater{} IO ()} which means
\texttt{print} argument type \texttt{a} is not a general type variable
but is constranined to take types which are an instance of
\texttt{Show}. Here \texttt{Show} is a type class.

Note that from \texttt{:info Show} it is clear that the standard types
like \texttt{Int}, \texttt{Bool} etc are all instances of the class
\texttt{Show}. Therefore the interpreter could print any value of those
type. However, a function type is not an instance of \texttt{Show} and
hence could not be printed.

\setcounter{chapter}{14}

\chapter{Monads and IO}

Will be up soon

\setcounter{chapter}{15}

\chapter{State monads}

Will be up soon

\setcounter{chapter}{16}

\chapter{Monad transformes}

Will be up soon

\setcounter{chapter}{17}

\chapter{Functions with varible number of arguments.}

Consider the printf function in C. The number of arguments it take
depends on the format string that is provided to it. Can one have
similar functions in Haskell ?

Let us analyse the type of \texttt{printf} in various expressions. In
the expression \texttt{printf "Hello"}, \texttt{printf} should have type
\texttt{String -\textgreater{} IO ()} where as in an expression like
\texttt{printf "Hello \%s" "world"}, it should have the type
\texttt{String -\textgreater{} String -\textgreater{} IO()}. This
chamelon like behaviour is what we need to define printf.

In this lecture we show how to hack Haskell's type class mechanism to
simulate such variable argument functions. The stuff we will do is
beyond Haskell 98 and hence we need to enable certain extensison. We do
it via the following compiler pragmas. The very first set of lines in
the source code if they are comments that start with \texttt{\{-\#} and
end with \texttt{\#-\}} are treated as compiler pragmas. In this case we
want to allow the extensions FlexibleInstances OverlappingInstances and
InvoherentInstances. One can also give these extensions at compile time;
to enable the extension Foo use the flag -XFoo at compile time.

Ofcourse it is difficult to remember all the extensions that you need
for this particular code to work. The easiest way to know what
extensions are required is to go ahead and use it in your file. GHC will
warn you with an appropriate error message if it expects an extension.

\begin{verbatim}

&gt; {-# LANGUAGE FlexibleInstances        #-}
&gt; {-# LANGUAGE OverlappingInstances     #-}
&gt; {-# LANGUAGE IncoherentInstances      #-}
&gt;
&gt; module Printf where
\end{verbatim}
Recall that an expression using printf would look something like the one
below.

\begin{verbatim}

printf fmt e1 e2 ... em
\end{verbatim}
We want our type system to infer \texttt{IO ()} for this expression. The
type of \texttt{printf} in such a case should be
\texttt{String -\textgreater{} t1 -\textgreater{} ... -\textgreater{} tm -\textgreater{} IO ()}
where \texttt{ti} is the type of \texttt{ei}. The main idea is to define
a type classes say \texttt{Printf} whose instances are precisely those
types that are of the form
\texttt{t1 -\textgreater{} ... -\textgreater{} tm -\textgreater{} IO ()}.
As a base case we will define an instance for \texttt{IO ()}. We will
then inductively define it for other types.

The definition of the type class \texttt{Printf} and therefore
\texttt{printf} will be easier if we first declare a data type for
formating.

\begin{verbatim}

&gt;
&gt; data Format = L String -- ^ A literal string
&gt;             | S        -- ^ %s
&gt;             | G        -- ^ %g for instances of Show
&gt;
&gt;
\end{verbatim}
We would rather work with the more convenient \texttt{{[}Format{]}}
instead of the format string. Writing a function to convert from format
string to \texttt{{[}Format{]}} is not too difficult.

Now for the actual definition of the \texttt{Printf} class.

\begin{verbatim}

&gt; class Printf s where
&gt;       printH :: IO [Format] -&gt; s
&gt;
\end{verbatim}
The member function \texttt{printH} of the class \texttt{Printf} is a
helper function that will lead us to definition of \texttt{printf}.
Intutively it takes as argument an IO action which prints whatever
arguments it has seen so far and returns the rest of the formating
action required to carry out s.

We will define the \texttt{Printf} instances for each of the type
\texttt{t1 -\textgreater{} ... tm -\textgreater{} I0 ()} inductively.
The base case is when there are no arguments.

\begin{verbatim}

&gt; instance Printf (IO ()) where
&gt;       printH fmtIO  = do fmt &lt;- printLit fmtIO
&gt;                          if null fmt then return ()
&gt;                             else fail "Too few arguments provided"
&gt;
\end{verbatim}
Now the inductive instance declaration.

\begin{verbatim}

&gt; instance (Printf s, Show a) =&gt; Printf (a -&gt; s) where
&gt;          printH fmtIO a = printH action
&gt;                 where action = do rfmt &lt;- printLit fmtIO
&gt;                                   case rfmt of
&gt;                                        []     -&gt; fail "Too many argument"
&gt;                                        (_:xs) -&gt; do putStr $ show a; return xs
\end{verbatim}
We give a specialised instance for string which depending on whether the
formating character is \%s or \%g uses putStr or print.

\begin{verbatim}

&gt;
&gt; instance Printf s =&gt; Printf (String -&gt; s) where
&gt;          printH fmtIO s = printH action
&gt;                 where action = do rfmt &lt;- printLit fmtIO
&gt;                                   case rfmt of
&gt;                                        [] -&gt; fail "Too many arguments"
&gt;                                        (G:xs) -&gt; do putStr $ show s; return xs
&gt;                                        (S:xs) -&gt; do putStr s; return xs
&gt;
\end{verbatim}
What is remaining is to define printLit

\begin{verbatim}

&gt;
&gt; printLit fmtIO = do fmt &lt;- fmtIO
&gt;                     let (lits,rest) = span isLit fmt
&gt;                         in do sequence_ [putStr x | L x &lt;- lits]
&gt;                               return rest
&gt; isLit (L _) = True
&gt; isLit  _    = False
&gt;
\end{verbatim}
We can now define printf

\begin{verbatim}

&gt; printf :: Printf s =&gt; String -&gt; s
&gt; printf = printH . format
&gt;
&gt; format :: String -&gt; IO [Format]
&gt; format ""         = return []
&gt; format "%"        = fail "incomplete format string"
&gt; format ('%':x:xs) = do fmts &lt;- format xs
&gt;                        case x of
&gt;                             's' -&gt; return (S:fmts)
&gt;                             'g' -&gt; return (G:fmts)
&gt;                             '%' -&gt; return (L "%" :fmts)
&gt;                             _   -&gt; fail ("bad formating character %" ++ [x])
&gt; format zs = let (lit,xs) = span (/='%') zs
&gt;             in do fmts &lt;- format xs
&gt;                   return (L lit:fmts)
&gt;
\end{verbatim}
\setcounter{chapter}{18}

\chapter{Template Haskell based implementation of \texttt{printf}}

In the last lecture we saw a type class based solution to create
functions that take variable number of arguments. Here we give a
template haskell based solution.

\section{What is Template Haskell ?}

Template haskell is the Haskell way of doing Meta programming. At the
very least one can use it like a macro substitution but it can be used
to do much more. The idea is to process the Haskell code at compile time
using Haskell itself. A programmer can write Haskell functions to
manipulate Haskell code and using special syntax arrange the compiler to
manipulate code at compile time. In this lecture we will see how to
define a version of printf using template haskell.

Template Haskell consists of two important steps.

\begin{enumerate}[1.]
\item
  Quoting: To allow user defined function to manipulate the Haskell code
  one needs to represent the program as a value in some suitable data
  type. The data types defined in the module
  \texttt{Language.Haskell.TH.Syntax} is used for this purpose. For
  example the type \texttt{Exp} defined in the above module is used to
  represent a valid Haskell expression. Have a look into the
  documentation of that module.
\item
  Splicing. Once the Haskell language fragment is processed using
  various function defined by the user, it needs to be compiled by the
  compiler. This processing is called splicing.
\end{enumerate}
One point to be noted though is that template haskell does not splice
the code directly but only those that are expressions that are inside
the quoting monad Q. This monad is required because while generate code
various side effects are created. For example a variable \texttt{x} used
in a fragment of the code has a different meaning if there is a local
binding defined on it. Besides one would want to read in data from files
(think of config files) to perform compile time operations.

There are two syantactic extensions to Haskell that makes template
Haskell possible. If a haskell expression is written between
\texttt{{[}\textbar{}} and \texttt{\textbar{}{]}}, the compiler will
replace it with the corresponding representation in
\texttt{Language.Haskell.TH.Syntax}. For example, the expression
\texttt{{[}\textbar{} "Hello" \textbar{}{]}} is of type \texttt{Q Exp}.
The corresponding \texttt{Exp} value is \texttt{LitE (StringL "Hello")}.

The following are the extra syntactic conventions used.

\begin{enumerate}[1.]
\item
  \texttt{{[}e\textbar{} ... \textbar{}{]}} or just
  \texttt{{[}\textbar{}} \ldots{} `\textbar{}{]}' for quoting
  expressions. This has type \texttt{Q Exp}.
\item
  \texttt{{[}d\textbar{} ... \textbar{}{]}} for quoting declarations.
  This has type \texttt{Q {[}Decl{]}}
\item
  \texttt{{[}t\textbar{} ... \textbar{}{]}} for quoting types. This has
  type \texttt{Q Type}.
\item
  \texttt{{[}p\textbar{} ... \textbar{}{]}} for quoting patterns. This
  has type \texttt{Q Pat}.
\end{enumerate}
The splicing is done using the syntax \texttt{\$(...)} (no space between
\texttt{\$} and \texttt{(})

\section{Some convenience types and combinators}

The types \texttt{Q Exp} and \texttt{Q Pat} etc occur so often that
there are aliases for them \texttt{ExpQ} and \texttt{PatQ} respectively.
As an exercise guess the types aliases for \texttt{Q Type} and
\texttt{Q Decl}.

Whenever possible it is better to make use of the
\texttt{{[}\textbar{} ... \textbar{}{]}} notation to build quoted
expressions. However sometimes it is better to use the constructors of
\texttt{Exp} directly. Recall that we can splice only quoted
expressions, i.e values of type Q Expr (or equivalently ExpQ). Say you
have a quoted expressions \texttt{qe} and \texttt{qf} which correspondes
to the haskell expression \texttt{e} and \texttt{f} respectively. If one
wants to obtaine the quoted expression which correspondes to the
application of the function \texttt{f} on the expression \texttt{e}, we
would have to do something like the following

\begin{verbatim}

qfe = do e &lt;- qe
         f &lt;- qf
     return $ AppE f e.
\end{verbatim}
To make this efficient there is a combinator called \texttt{appE} which
does essentially what the constructor \texttt{AppE} does but works on
\texttt{Q Exp} rather than \texttt{Exp}.

\begin{verbatim}

appE :: ExpQ -&gt; ExpQ -&gt; ExpQ
\end{verbatim}
The above code will then look like \texttt{appE qe qf}. There are such
monadic version of all the constructors of \texttt{Exp} available. Make
use of it.

\section{Printf}

First note that we have enabled template Haskell using the compiler
pragma given above. It should be the very first line of your source
code. A unrecognised pragma is ignored by the compiler but sometimes a
warning is issued.

\begin{verbatim}

&gt; {-# LANGUAGE TemplateHaskell    #-}
&gt; module Printf where
&gt; import Data.List
&gt; import Language.Haskell.TH
\end{verbatim}
Few things about enabling the template haskell. Strictly speaking this
module does not need TemplateHaskell, rather it can be written without
using template Haskell. This is because all it does is define functions
that process objects of type \texttt{Expr} or \texttt{ExprQ}. I have
enabled it so as to write \texttt{appE {[}\textbar{}show\textbar{}{]}}
instead of the more complicated. \texttt{appE (varE 'show)}

First let us capture the formating via a data type

\begin{verbatim}

&gt; data Format = L String    -- ^ literal string
&gt;             | S           -- ^ %s
&gt;             | G           -- ^ %g generic type
&gt;             deriving Show
\end{verbatim}
We need a function that will parse a string and the give the
corresponding list for format. The exact details are not really of
interest as far as template haskell is concerned. See the end of the
file for an implementation.

\begin{verbatim}

&gt; format :: String -&gt; [Format]
\end{verbatim}
The printf function can then be defined as.

\begin{verbatim}

&gt; printf  :: String -&gt; ExpQ
&gt; printfP :: [Format] -&gt; ExpQ
&gt; printf = printfP . format
\end{verbatim}
We would rather implement the prinfP function. Let the list of
formatting instructions be {[}f\_1,..,f\_n{]}, then we want
\texttt{prinfP {[}f\_1,...,f\_n{]}} when spliced to return the code.

\begin{verbatim}

\ x0  ... xm -&gt; concat [e1,...,e_n]
\end{verbatim}
Here e\_i depends on the ith format instruction f\_i. If f\_i is a
literal then it will just be a literal string. Otherwise it would be an
appropriate variable. In our case it should be \texttt{xj} where
\texttt{j} is the number of \emph{non-literal}, i.e. \texttt{S} or
\texttt{G}, formating instructions to the left of e\_i. The number $m$
is the total number of \emph{non-literal} formatting instructions in the
list {[}f\_1,\ldots{},f\_n{]} and should be less than or equal to n.

Suppose we know the number of variables to the left of a format
instruction f\_i, how do we generate the expression e\_i ? The following
function does that

\begin{verbatim}

&gt; toExpQ :: Int         -- ^ formatting instructions to the left
&gt;        -&gt; Format      -- ^ The current spec.
&gt;        -&gt; (Int,ExpQ)  -- ^ The total number of non-literal instruction
&gt;               -- to the left and the resulting expression.
&gt; toExpQ i   (L s) = (i,string s)
&gt; toExpQ i   S     = (i+1,varExp i)
&gt; toExpQ i   G     = (i+1,showE $ varExp i)
\end{verbatim}
Here we make use of the following helper Template haskell functions
which we have defined subsequently.

\begin{verbatim}

&gt; string  :: String -&gt; ExpQ  -- ^ quote the string
&gt; showE   :: ExpQ   -&gt; ExpQ  -- ^ quoted showing
&gt; varExp  :: Int    -&gt; ExpQ  -- ^ quoted variable xi
&gt; varPat  :: Int    -&gt; PatQ  -- ^ quoted pattern xi
\end{verbatim}
The printfP function then is simple. Recall that when spliced it should
generate the expression

\begin{verbatim}
       \ x0 ... xm -&gt; concat [e1,...,e_n]`
\end{verbatim}
The complete definition is given below.

\begin{verbatim}

&gt; printfP fmts = lamE args . appE conc $ listE es
&gt;         where (nvars,es) = mapAccumL toExpQ 0 fmts
&gt;               args       = map varPat [0 .. (nvars-1)]
&gt;               conc       = [|concat|]
\end{verbatim}
Here are the definition of the helper functions

\begin{verbatim}

&gt; string   = litE . StringL
&gt; varExp i = varE $ mkName ("x" ++ show i)
&gt; varPat i = varP $ mkName ("x" ++ show i)
&gt; showE    = appE [|show|]
\end{verbatim}
We now come to the parsing of the format string. For simplicity of
implementation if \% occurs before an unknow format string it is treated
as literal occurance.

\begin{verbatim}

&gt; format ""             = []
&gt; format ['%']          = [L "%"]
&gt; format ('%':x:xs)
&gt;        | x == 's'  = S : format xs
&gt;        | x == 'g'  = G : format xs
&gt;        | x == '%'  = L "%" : format xs
&gt;        | otherwise = L ['%',x] : format xs
&gt; format zs          = L x : format xs
&gt;        where (x,xs) = span (/='%') zs
\end{verbatim}
To try it out load it with ghci using the option -XTemplateHaskell. You
need this option to tell ghci that it better expect template haskell
stuff like Oxford bracket \texttt{{[}\textbar{} \textbar{}{]}} and
splicing \texttt{\$(...)}

\begin{verbatim}

$ ghci -XTemplateHaskell src/lectures/Template-Haskell-based-printf.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 Printf           ( src/lectures/Template-Haskell-based-printf.lhs, interpreted )
Ok, modules loaded: Printf.
*Printf&gt; $(printf "%s is a string") "Hello"
"Hello is a string"
*Printf&gt; $(printf "%s is a string %g is an int") "Hello" 10
"Hello is a string 10 is an int"
*Printf&gt;
\end{verbatim}
\section{Exercise}

\begin{enumerate}[1.]
\item
  Write a function that will optimise the format instructions by merging
  consecutive literal strings. Is there any point in optimising the
  format instructions?
\item
  Rewrite the printf module to not use any template haskell itself.
\end{enumerate}
\setcounter{chapter}{19}

\chapter{Concurrent programming in Haskell}

Haskell has a very good support for concurrent programming. In this
lecture we see a very basic introduction to concurrent programming.

\section{Threads}

The Haskell runtime implements threads which are really lightweight.
This means that on a decent machine you can open say 10K threads and
still be have decent performance. This makes Haskell a great platform to
implement high connectivity servers like http/ftp servers etc.

However you need to be carefull about FFI calls to C code. If one of
your thread makes a call to a C function that blocks then all the
threads will block. Sometimes the call to C functions might be indirect,
you might use a library that uses Haskells FFI to talk to an already
implemented C library. Then you can be in trouble if you are not
careful.

One creates threads in Haskell using the
\texttt{forkIO :: IO () -\textgreater{} IO ThreadId} function. The
threads created using \texttt{forkIO} are really local to you ghc
process and will not be visible in the rest of the OS. There is a
similar \texttt{forkOS} function that creates an OS level thread. As
long as the code uses pure haskell functions \texttt{forkIO} is all that
you need.

We give here a basic function that forks a lot of worker process. The
module to import is \texttt{Control.Concurrent}.

\begin{verbatim}

&gt; import Control.Concurrent -- Concurrency related module
&gt; import System.Environment -- For command line args in main

\end{verbatim}
This is the worker process. In real life program this is were stuff
happen.

\begin{verbatim}

&gt; worker :: Int -&gt; IO ()
&gt; worker inp = do tId &lt;- myThreadId
&gt;                 let say x = putStrLn (show tId ++ ": " ++ x)
&gt;                     in do say ("My input is " ++ show inp)
&gt;                           say "Oh no I am dying."
&gt; 
\end{verbatim}
Here is where the process is created. Note that \texttt{forkIO . worker}
takes as input an integer and runs the worker action on it in a seperate
thread

\begin{verbatim}

&gt; runThreads :: [Int] -&gt; IO ()
&gt; runThreads = sequence_ . map (forkIO . worker) 
&gt; 
\end{verbatim}
And finally this is the main function where all the command line
arguments are parsed and things done.

\begin{verbatim}

&gt; main = do args &lt;- getArgs
&gt;           case args of
&gt;                [a] -&gt; let nthreads = read a
&gt;                           in runThreads [1..nthreads]
&gt;                _   -&gt; putStrLn "Bad arguments"
&gt; 
\end{verbatim}
\section{Daemonic thread termination}

There is a big bug in the code you just saw. All threads are terminated
as soon as the main thread terminates. For real world applications one
wants main thread to hang around till the others are done. We will see
one way to handle this in the next lecture.

\begin{center}\rule{3in}{0.4pt}\end{center}

\emph{Last modified on Monday (31 October 2011 10:14:13 UTC)}

\end{document}
</pre></body></html>