% mrh 17/1 2013
% $Header: /cvsroot/latex-beamer/latex-beamer/solutions/generic-talks/generic-ornate-15min-45min.en.tex,v 1.5 2007/01/28 20:48:23 tantau Exp $
\documentclass[9pt,xcolor=dvipsnames]{beamer}
%\documentclass[handout,9pt,xcolor=dvipsnames]{beamer}


\mode<presentation>
{
  \usetheme{DTU}
  % or ...


  \setbeamercovered{transparent}

  % or whatever (possibly just delete it)
}

\usepackage[english]{babel}
% or whatever

\usepackage[latin1]{inputenc}
% or whatever

\usepackage{palatino}
%\usepackage[T1]{fontenc}
\usepackage{mrhalltt}
\usepackage{itemlist}
%\usepackage{fix-cm}

\input{macros}

% Or whatever. Note that the encoding and the font should match. If T1
% does not look nice, try deleting the line with the fontenc.

%\usepackage{pgfpages}
%\pgfpagesuselayout{4 on 1}[letterpaper,landscape,bordershrink=5mm]

\title % (optional, use only with long paper titles)
{02157 Functional Programming}

\subtitle
{Lecture 3: Lists} % (optional)

\author% (optional, use only with lots of authors)
{Michael~R.~Hansen}
% - Use the \inst{?} command only if the authors have different
%   affiliation.

\institute % (optional, but mostly needed)
{DTU Informatics, Technical University of Denmark}

\date {MRH 17/09/2012}% (optional)
%{Advanced Topics on Embedded Systems}

%\subject{Talks}


 \pgfdeclareimage[height=.75cm]{university-logo}{DTUlogo}
 \logo{\pgfuseimage{university-logo}}

 \pgfdeclareimage[height=3.3cm]{frise}{DTUfrise}
 \pgfdeclareimage[height=.8cm]{dept}{DTUInformatics}


% If you wish to uncover everything in a step-wise fashion, uncomment
% the following command:

%\beamerdefaultoverlayspecification{<+->}

\begin{document}

\begin{frame}
  \titlepage
%  \begin{tabular}{p{5cm}p{10cm}}
%    &\pgfuseimage{frise}\\
%    \pgfuseimage{dept} &
%  \end{tabular}

\end{frame}


\begin{frame}{Overview}

\begin{itemize}

\item Generation of lists

\medskip

\item Useful functions on lists

\medskip

\item Typical recursions on lists

\medskip

\item Programming as a modelling activity\\
-- Cash register\\
-- Map coloring

\end{itemize}

\end{frame}

\begin{frame}[fragile]{Range expressions (1)}
A {\redbrown simple range expression} $\blue [b\ \verb-..-\ e]$, where $\blue e\ge b$, generates the list:
\[\blue
[b; b+1; b+2; \ldots ; b+n]
\]
where $\blue n$ is chosen such that $\blue b+n \le e < b+n+1$.

\medskip
\pause

Example
\begin{alltt}\blue
[ -3 .. 5 ];;
\ett{val it : int list = [-3; -2; -1; 0; 1; 2; 3; 4; 5]}
\end{alltt}

\medskip
\pause

\begin{alltt}\blue
[2.4 .. 3.0 ** 1.7];;
\ett{val it : float list = [2.4; 3.4; 4.4; 5.4; 6.4]}
\end{alltt}
\pause Note that {\blue \verb-3.0 ** 1.7 = 6.47300784-}.

\medskip\pause

The range expression generates the empty list when $\blue e<b$:
\begin{alltt}\blue
[7 .. 4];;
\ett{val it : int list = []}
\end{alltt}


\end{frame}

\begin{frame}[fragile]{Range expressions (2)}
The range expression $\blue [b\ \mathtt{..}\ s\ \mathtt{..}\ e]$ generates
either an ascending or a descending list:
\[\blue
\begin{array}{l}
[b\ \mathtt{..}\ s\ \mathtt{..}\ e]
\ = \ [b; b+s; b+2s; \ldots ; b + n s]\\[2mm]  
\mbox{where} \qquad \left\{\begin{array}{ll}
\mbox{$b+n s \le e < b+(n+1)s$} & \text{if $s>0$}\\
\mbox{$b+n s \ge e > b+(n+1)s$}  & \text{if $s<0$}\\
\end{array}\right.
\end{array}\]
depending on the sign of $\blue s$.

\medskip
\pause

Examples:
\begin{alltt}\blue
[6 .. -1 .. 2];;
\ett{val it : int list = [6; 5; 4; 3; 2]}
\end{alltt}
\pause
and the float representation of $\blue 0, \pi/2, \pi, \frac{3}{2}\pi, 2\pi$ is generated by:
\begin{alltt}\blue
[0.0 .. System.Math.PI/2.0 .. 2.0*System.Math.PI];;
\ett{val it : float list =}
\ett{  [0.0; 1.570796327; 3.141592654; 4.71238898; 6.283185307]}
\end{alltt}
\end{frame}


\begin{frame}[fragile]\frametitle{Simple recursion on lists}

We consider now three simple functions:
\begin{itemize}
\item append
\item reverse
\item isMember
\end{itemize}
whose declarations follow the structure of lists
\begin{alltt}\blue
let rec \(f\) ... xs ... =
    | []    -> \(v\)
    | x::xs -> .... \(f\) xs ...
\end{alltt}
using just two clauses.
\end{frame}




\begin{frame}[fragile]\frametitle{Append}

The infix operator {\blue \verb/@/} (called `append') joins two
lists:
\[\begin{array}{l}
\verb?[?x_1\verb?;? x_2\verb?;? \ldots \verb?;? x_{m}\verb?]?\
\verb/@/\
\verb?[?y_1\verb?;? y_2\verb?;? \ldots \verb?;? y_{n}\verb?]?\\
\qquad \qquad  = \verb?[?x_1\verb?;? x_2\verb?;? \ldots \verb?;?
x_{m}\verb?;? y_1\verb?;? y_2\verb?;? \ldots \verb?;?
y_{n}\verb?]?
\end{array}
\]

\pause
Properties
\[
\begin{array}{rcl}
\verb?[]?\ \verb/@/\ \mathit{ys}
%\verb?[?y_1\verb?,? y_2\verb?,? \ldots\verb?,?
%y_{n}\verb?]?
&=& \mathit{ys}\\
%\verb?[?y_1\verb?,? y_2\verb?,? \ldots \verb?,? y_{n}\verb?]? \\
%\lbrack x_1, x_2, \ldots , x_{m}]\ \verb/@/\ [y_1, y_2, \ldots ,
%y_{n}]
\verb?[? x_1\verb?;? x_2\verb?;? \ldots \verb?;? x_{m}\verb?]?\
\verb/@/\ \mathit{ys}
%\verb?[?y_1\verb?,? y_2\verb?,? \ldots\verb?,? y_{n}\verb?]?
&=& x_1 \verb?::? (\verb?[?x_2 \verb?;? \ldots \verb?;?
x_{m}\verb?]?\ \verb/@/\ \mathit{ys})
%\verb?[?y_1\verb?,? y_2\verb?,? \ldots \verb?,? y_{n}\verb?]?)
\end{array}
\]

\pause Declaration {\blue
\begin{alltt}
let rec (@) xs ys =
  match xs with
  | []     -> ys
  | x::xs' -> x::(xs' @ ys);;
\ett{val (@) : 'a list -> 'a list -> 'a list}
\end{alltt}
}
\end{frame}




\begin{frame}[fragile]\frametitle{Append: evaluation}
\begin{verbatim}
let rec (@) xs ys =
  match xs with
  | []     -> ys
  | x::xs' -> x::(xs' @ ys);;
\end{verbatim}

\bigskip

Evaluation
\[\blue
\begin{array}{llll}
     & \verb/[1,2] @ [3,4]/ &\\
\lto & \verb/1::([2] @ [3,4])/ & (\mathtt{x} \mapsto 1,\
\mathtt{xs'} \mapsto [2],\ \mathtt{ys} \mapsto [3,4]) \\
\lto & \verb/1::(2::([] @ [3,4]))/ & (\mathtt{x} \mapsto 2,\
\mathtt{xs'} \mapsto [\, ],\
\mathtt{ys} \mapsto [3,4])\\
\lto & \verb/1::(2::[3,4])/ &(\mathtt{ys} \mapsto [3,4])\\
\lto & \verb/1::[2,3,4]/ &\\
\lto & \verb/[1;2;3;4]/ &
\end{array}
\]

\pause
\begin{itemize}
\item {\redbrown Execution time is linear in the size of the first
list}
\end{itemize}
\end{frame}



\begin{frame}[fragile]\frametitle{Append: polymorphic type}

The answer from the system is:
\begin{verbatim}
> val (@) : 'a list -> 'a list -> 'a list
\end{verbatim}

%\medskip

\begin{itemize}
\item \verb-'a- is a {\blue\em type variable}


\item The type of \verb-@- is {\blue\em polymorphic} --- it has
many forms
\end{itemize}

\bigskip \pause

\begin{description}
\item[{\darkgreen \texttt{'a} = \texttt{int}}:] Appending integer
lists
%(\verb-'a- = \verb-int-)

\begin{alltt}
[1;2] @ [3;4];;
\ett{val it : int list = [1;2;3;4]}
\end{alltt}

\pause
\item[{\darkgreen \texttt{'a} = \texttt{int list}}:]
Appending lists of integer list

\begin{alltt}
[[1];[2;3]] @ [[4]];;
\ett{val it : int list list = [[1]; [2; 3]; [4]]}
\end{alltt}
\end{description}


\bigskip

\begin{center}\redbrown
\verb-@- is a built-in function
\end{center}

\end{frame}


\begin{frame}[fragile]\frametitle{Reverse\  \hspace{1cm}
$ {\tt rev}\; [ x_1; x_2; \ldots ;
     x_{n} ]
 =  [ x_{n} ; \ldots ; x_2 ; x_1]
$} \vspace{-.3cm}
\begin{alltt}\blue
let rec naive_rev = function
 | []    -> []
 | x::xs -> naive_rev xs @ [x];;
\ett{val naive_rev : 'a list -> 'a list}
\end{alltt}

\pause
An evaluation:
\[\blue
\begin{array}{ll}
     & \verb/naive_rev[1;2;3]/\\
\lto & \verb/naive_rev[2;3] @ [1]/\\
\lto & \verb/(naive_rev[3] @ [2]) @ [1]/\\
\lto & \verb/((naive_rev[] @ [3]) @ [2]) @ [1]/\\
\lto & \verb/(([] @ [3]) @ [2]) @ [1]/\\
\lto & \verb/([3] @ [2]) @ [1]/\\
\lto & \verb/(3::([] @ [2])) @ [1]/\\
\lto & \verb/(3::[2]) @ [1]/\\
\lto & \verb/[3;2] @ [1]/\\
\lto & \verb/3::([2] @ [1])/\\
\lto & \ldots\\
%\lto & \verb/3 :: (2 :: ([] @ [1]))/\\
%\lto & \verb/3 :: (2 :: [1])/\\
%\lto & \verb/3 :: [2;1]/\\
\lto & \verb/[3;2;1]/
\end{array}
\]

\pause
\medskip
\begin{center}\blue Takes $O(n^2)$ time  \pause ---
\darkgreen Built-in version (\verb-List.rev-) is efficient $O(n)$\\
We consider efficiency later.
\end{center}
\end{frame}


\begin{frame}[fragile]\frametitle{Membership --- equality types}
\[\blue
\begin{array}{ll}
   &  \verb?isMember?\ x\ \verb?[?y_1\verb?;?y_2\verb?;?\ldots\verb?;?y_n\verb?]?\\
 = & (x = y_1)\ \vee\ (x = y_2) \vee\ \cdots\ \vee (x = y_n)\\
 = & (x = y_1)\ \vee\ (\verb?member?\ x\ \verb?[?y_2\verb?,?
                                    \ldots\verb?,? y_n\verb?]?)
\end{array}
\]

\pause

Declaration
\begin{alltt}\blue
let rec isMember x = function
| []    -> false
| y::ys -> x=y || isMember x ys;;
\ett{val isMember : 'a -> 'a list -> bool when {\redbrown 'a : equality}}
\end{alltt}


\pause

\begin{itemize}
\item\mbox{} \mbox{\redbrown{\tt 'a}} is an {\blue equality type
variable} \hfill
  {\darkgreen no function types}

\item \verb-isMember (1,true) [(2,true); (1,false)]- $\lto$ false
\item  \verb-isMember [1;2;3]  [[1]; []; [1;2;3]]- $\lto$ true
\end{itemize}
\end{frame}


\begin{frame}[fragile]\frametitle{Match on results of recursive call}

We consider declarations on the form:
\begin{alltt}\blue
let rec \(f\) ... xs ... =
    ....
    let \(\mathit{pat}(\overline{y})\) = \(f\) xs
    \(e(\overline{y})\)
\end{alltt}

\bigskip

Recall unzip and split from last week.

\end{frame}




\begin{frame}[fragile]\frametitle{Example: \texttt{sumProd}}

\medskip
\begin{tabular}{lcl}
\multicolumn{3}{l}{
  {\tt sumProd}\ {\tt [}$x_0${\tt ;}$x_1${\tt ;} $\ldots${\tt ;}$x_{n-1}${\tt ]}
} \\
 & = &
{\tt (} $x_0$ {\tt +} $x_1$ {\tt +} $\ldots$ {\tt +} $x_{n-1}$ {\tt ,}
  $x_0$ {\tt *} $x_1$ {\tt *} $\ldots$ {\tt *} $x_{n-1}$ {\tt )} %\\
% {\tt sumProd []} &=& {\tt (0,1)}
\end{tabular}

\pause
\bigskip

The declaration is based on the recursion formula:
\[\begin{array}{l}{\blue
\texttt{sumProd}\ \texttt{[}x_0\texttt{;}x_1\texttt{;}
  \ldots\texttt{;}x_{n-1}\texttt{]} =
  \texttt{(}x_0\ \texttt{+}\ \texttt{rSum} \texttt{,} x_0\ \texttt{*}\ \texttt{rProd} \texttt{)}}\\
\mbox{where $\blue \texttt{(rSum,rProd)} =
\texttt{sumProd}\ \texttt{[}x_1\texttt{;}
  \ldots\texttt{;}x_{n-1}\texttt{]}$}
\end{array}
\]

\medskip
\pause

This gives the declaration
\begin{alltt}
let rec sumProd = function
    | []   -> (0,1)
    | x::rest ->
          {\blue let (rSum,rProd) = sumProd rest
           (x+rSum,x*rProd)};;
\ett{val sumProd : int list -> int * int}

sumProd [2;5];;
\ett{val it : int * int = (7, 10)}
\end{alltt}

\end{frame}

\begin{frame}[fragile]\frametitle{Example: \texttt{split}}

\medskip
Declare an F\# function \texttt{split} such that:
\[
\mathtt{split}\; \texttt{[}x_0\texttt{;} x_1\texttt{;} x_2\texttt{;} x_3\texttt{;}
\ldots\texttt{;} x_{n-1}\texttt{]} =  (\texttt{[}x_0\texttt{;}  x_2\texttt{;} \ldots
\texttt{]}, \texttt{[}x_1\texttt{;} x_3\texttt{;} \ldots \texttt{]} )
\]

\pause
\bigskip

The declaration is
\begin{alltt}
let rec split = function
    | []       -> ([],[])
    | [x]      -> ([x],[])
    | x::y::xs ->{\blue let (xs1,xs2) = split xs
                  in (x::xs1,y::xs2)};;
\end{alltt}

\medskip
\pause
Notice
\begin{itemize}
\item a convenient division into three cases, and
\item the recursion formula
\[\begin{array}{l}{\blue
\texttt{split}\ \texttt{[}x_0\texttt{;}x_1\texttt{;}x_2\texttt{;}
  \ldots\texttt{;}x_{n-1}\texttt{]} =
  \texttt{(}x_0\ \texttt{::}\ \texttt{xs1} \texttt{,} x_1\ \texttt{::}\ \texttt{xs2} \texttt{)}}\\
\mbox{where $\blue \texttt{(xs1,xs2)} =
\texttt{split}\ \texttt{[}x_2\texttt{;}
  \ldots\texttt{;}x_{n-1}\texttt{]}$}
\end{array}
\]
\end{itemize}
\end{frame}

\begin{frame}{The problem}
\begin{quote}
An electronic cash register contains a data register associating
the name of the article and its price to each valid article code.
A purchase comprises a sequence of items, where each item
describes the purchase of one or several pieces of a specific
article.

\bigskip
\pause

The task is to construct a program which makes a bill of a
purchase. For each item the bill must contain the name of the
article, the number of pieces, and the total price, and the bill
must also contain the grand total of the entire purchase.
\end{quote}

\end{frame}

\begin{frame}{Goal and approach}

Goal: the main concepts of the problem formulation are traceable
in the program.

\bigskip
\pause

Approach: to name the important concepts of the problem and
associate types with the names.
\begin{itemize}
\item This model should facilitate discussions about whether it
fits the problem formulation.
\end{itemize}

\bigskip
\pause

Aim: A succinct, elegant program reflecting the model.

\end{frame}

\begin{frame}{The problem}
\begin{quote}
An electronic cash register contains a data {\darkgreen register}
associating the {\darkgreen name} of the {\darkgreen article} and
its {\darkgreen price} to each valid {\darkgreen article code}. A
{\darkgreen purchase} comprises a {\darkgreen sequence of items},
where each {\darkgreen item} describes the purchase of one or
several pieces of a specific article.

\bigskip
\pause

The task is to construct a program which makes a {\darkgreen bill}
of a purchase. For each item the bill must contain the name of the
article, the {\darkgreen number of pieces}, and the {\darkgreen
total price}, and the bill must also contain the {\darkgreen grand
total} of the entire purchase.
\end{quote}

\end{frame}


\begin{frame}[fragile]\frametitle{A Functional Model}

\begin{itemize}
\item Name key concepts and give them a type
\end{itemize}

\pause

A signature for the cash register:

\begin{center}\small
\begin{tabular}{|l|}
\hline
\verb/type articleCode = string/ \\
\verb/type articleName = string/ \\
\verb/type price       = int/  \\
\verb/type register    = (articleCode * (articleName*price)) list/ \\
\verb/type noPieces    = int/   \\
\verb/type item        = noPieces * articleCode/ \\
\verb/type purchase    = item list/ \\
\verb/type info        = noPieces * articleName * price/ \\
\verb/type infoseq     = info list/ \\
\verb/type bill        = infoseq * price/ \\
\\
\verb/makeBill: register -> purchase -> bill/ \\

\hline
\end{tabular}
\end{center}

\pause\medskip

\begin{center}\redbrown
Is the model adequate?
\end{center}
\end{frame}

\begin{frame}[fragile]\frametitle{Example}

The following declaration names a register:
\begin{alltt}
let reg = [("a1",("cheese",25));
           ("a2",("herring",4));
           ("a3",("soft drink",5)) ];;
\end{alltt}

\pause
\medskip

The following declaration names a purchase:
\begin{alltt}
let pur = [(3,"a2"); (1,"a1")];;
\end{alltt}

\pause
\medskip

A bill is computed as follows:
\begin{alltt}
makeBill reg pur;;
\ett{val it : (int * string * int) list * int =}
\ett{  ([(3, "herring", 12); (1, "cheese", 25)], 37)}
\end{alltt}
\end{frame}

\begin{frame}[fragile]\frametitle{Functional decomposition (1)}

Type: {\redbrown findArticle: articleCode $\to$ register $\to$ articleName * price}

\begin{alltt}
let rec findArticle ac = function
    | (ac',adesc)::_ when ac=ac' -> adesc
    | _::reg                     -> findArticle ac reg
    | _                          ->
          {\redbrown failwith(ac + " is an unknown article code")};;
\ett{val findArticle : string -> (string * 'a) list -> 'a}
\end{alltt}
Note that the specified type is an instance of the inferred type.

\pause
\bigskip

An article description is found as follows:
\begin{alltt}
findArticle "a2" reg;;
\ett{val it : string * int = ("herring", 4)}

findArticle "a5" reg;;
\ett{System.Exception: a5 is an unknown article code}
\ett{   at FSI_0016.findArticle[a] ... }
\end{alltt}
Note: {\redbrown failwith} is a built-in function that raises an exception

\end{frame}


\begin{frame}[fragile]\frametitle{Functional decomposition (2)}

{\blue Type: {\redbrown makeBill: register $\to$ purchase $\to$ bill}}
\begin{alltt}
let rec makeBill reg = function
    | []           -> ([],0)
    | (np,ac)::pur ->
         let (aname,aprice) = findArticle ac reg
         let tprice         = np*aprice
         let (billtl,sumtl) = makeBill reg pur
         ((np,aname,tprice)::billtl, tprice+sumtl);;
\end{alltt}

\medskip
\pause
The specified type is an instance of the inferred type:
\begin{alltt}\blue
\ett{val makeBill :}
\ett{    (string * ('a * int)) list -> (int * string) list}
\ett{                -> (int * 'a * int) list * int}
\end{alltt}

\medskip
\pause

\begin{alltt}
makeBill reg pur;;
\ett{val it : (int * string * int) list * int =}
\ett{  ([(3, "herring", 12); (1, "cheese", 25)], 37)}


\end{alltt}

\end{frame}

\begin{frame}[fragile]\frametitle{Patterns with guards: Three versions of \texttt{findArticle}}

An if-then-else expression in
\begin{alltt}
let  rec findArticle ac = function
   | (ac',adesc)::reg -> if ac=ac' then adesc
                         else findArticle ac reg
   | _   -> failwith(ac + " is an unknown article code");;
\end{alltt}

\medskip
\pause
may be avoided using clauses with {\redbrown guards}:
\begin{alltt}
let  rec findArticle ac = function
   | (ac',adesc)::reg{\redbrown when ac=ac'} -> adesc
   | (ac',adesc)::reg             -> findArticle ac reg
   | _   -> failwith(ac + " is an unknown article code");;
\end{alltt}

\medskip
\pause
This may be simplified using wildcards:
\begin{alltt}
let  rec findArticle ac = function
   | (ac',adesc)::_{\redbrown when ac=ac'} -> adesc
   | _::reg                     -> findArticle ac reg
   | _   -> failwith(ac + " is an unknown article code");;
\end{alltt}

\end{frame}


\begin{frame}{Summary}

\begin{itemize}
\item A succinct model is achieved using type declarations.

\item<2-> Easy to check whether it fits the problem.

\item<3-> Conscious choice of variables (on the basis of the
model) increases readability of the program.

\item<4-> Standard recursions over lists solve the problem.
\end{itemize}

\end{frame}



\begin{frame}{Example: Map Coloring.}

{\redbrown A map should be colored so that neighbouring countries
get different colors}

\bigskip

{\setlength{\unitlength}{.5\unitlength}
\begin{center}
{\small
\begin{picture}(140,80)(0,15)

\put(0,30){\framebox(40,40)}

\put(20,50){\makebox(0,0){\tt "b"}}

\put(40,20){\framebox(40,40)}

\put(60,40){\makebox(0,0){\tt "a"}}

\put(80,40){\framebox(40,40)}

\put(100,60){\makebox(0,0){\tt "d"}}

\put(100,0){\framebox(40,40)}

\put(120,20){\makebox(0,0){\tt "c"}}

\end{picture}
}
\end{center}
}

\bigskip

\onslide<2->{The types for country and map are ``straightforward'':}
\begin{itemize}

\item<2-> \texttt{\blue type country = string} \\[2mm]
\onslide<3->{Symbols: {\darkgreen c, c1, c2, c'};\ \ Examples:
"a", "b", $\ldots$}

\medskip

\item<4-> \texttt{\blue type map=(country*country) list} \\[2mm]
\onslide<5->{Symbols: {\darkgreen m};\ \ Example: val exMap =
[("a","b"); ("c","d"); ("d","a")]}

\end{itemize}

\pause[5]
\begin{center}\redbrown
How many ways could above map be colored?
\end{center}
\end{frame}

\begin{frame}[fragile]\frametitle{Abstract models for color and coloring}

\begin{itemize}
\item<1->
\texttt{\blue type color            = country list}\\[2mm]
\onslide<2->{Symbols: {\darkgreen col};\ \ Example: ["c"; "a"]}

\medskip

\item<3->
\texttt{\blue type coloring         = color list}\\[2mm]
\onslide<4->{Symbols: {\darkgreen cols};\ \ Example: [["c"; "a"];
["b"; "d"]]}
\end{itemize}
\ \hfill \onslide<1->{\em\redbrown Be conscious about symbols and
examples}

\pause[5]
\medskip
{\blue
\begin{alltt}
   colMap:  map -> coloring
\end{alltt}
}

\pause[6]

\begin{figure}[h]
{\small
\begin{tabular}{@{}l@{}|@{}l@{}|@{}l@{}}
%\ \ \ \ \ \ \ \ \ \ \
 \textbf{Meta symbol: Type\ }  & \textbf{\ Definition} & \textbf{Sample value}\\ \hline
%\cline{2-4}
 \verb/c:    country/ &  \verb/string/
   & \verb/"a"/  \\
 \verb/m:    map/ & \verb/(country*country) list/
  & \verb/[("a","b"),("c","d"),("d","a")]/ \\
 \verb/col:  color/ &  \verb/country list/
  & \verb/["a","c"]/ \\
 \verb/cols: coloring/ & \verb/color list/
  & \verb/[["a","c"],["b","d"]]/ \\
\end{tabular}}
\caption{\label{DataModelFigure} A Data model for map coloring problem}
\end{figure}
\end{frame}



\begin{frame}[fragile]\frametitle{Algorithmic idea}

{\setlength{\unitlength}{.5\unitlength}
\begin{center}
{\small
\begin{picture}(140,80)(0,15)

\put(0,30){\framebox(40,40)}

\put(20,50){\makebox(0,0){\tt "b"}}

\put(40,20){\framebox(40,40)}

\put(60,40){\makebox(0,0){\tt "a"}}

\put(80,40){\framebox(40,40)}

\put(100,60){\makebox(0,0){\tt "d"}}

\put(100,0){\framebox(40,40)}

\put(120,20){\makebox(0,0){\tt "c"}}

\end{picture}
}
\end{center}
}

\bigskip

Insert repeatedly countries in a coloring.

\bigskip

\begin{figure}[h]
{\small
\begin{tabular}{@{}l|c|l|l@{}}
 & country & old coloring & new coloring \\ \hline
1.   & \texttt{"a"} & \verb+[]+      & \verb+[["a"]]+\\
2.   & \texttt{"b"} & \verb+[["a"]]+ & \verb+[["a"] ; ["b"]]+\\
3.   & \texttt{"c"} & \verb+[["a"] ; ["b"]]+ & \verb+[["a";"c"] ; ["b"]]+\\
4.   & \texttt{"d"} & \verb+[["a";"c"] ; ["b"]]+ &
          \verb+[["a";"c"] ; ["b";"d"]]+
\end{tabular}
}
\caption{\label{Idea}Algorithmic idea}
\end{figure}

\end{frame}

\begin{frame}[fragile]\frametitle{Functional decomposition (I)}

\ \hfill {\darkgreen To make things easy}\\

\pause
Are two countries neighbours?

\begin{center} \redbrown areNb:
map $\to$ country $\to$ country  $\to$ bool
\end{center}

{\blue
\begin{verbatim}
let areNb m c1 c2 = isMember (c1,c2) m || isMember (c2,c1) m;;
\end{verbatim}
}

\pause
\bigskip

Can a color be extended?
\begin{center} \redbrown
canBeExtBy: map $\to$ color $\to$ country $\to$ bool
\end{center}

\pause
{\blue
\begin{alltt}
let rec canBeExtBy m col c =
  match  col with
  | []       -> true
  | c'::col' -> not (areNb m c' c) && canBeExtBy m col' c;;

canBeExtBy exMap ["c"] "a";;
\ett{val it : bool = true}

canBeExtBy exMap ["a"; "c"] "b";;
\ett{val it : bool = false}
\end{alltt}
}

\end{frame}


\begin{frame}[fragile]\frametitle{Functional composition (I)}
\ \hfill {\darkgreen Combining functions make things easy}\\

\pause
Extend a coloring by a country:
\begin{center}\redbrown
extColoring: map $\to$ coloring $\to$ country $\to$ coloring
\end{center}

\bigskip

{\darkgreen
\begin{verbatim}
Examples:
  extColoring exMap [] "a"       =  [["a"]]
  extColoring exMap [["b"]] "a"  =  [["b"] ; ["a"]]
  extColoring exMap [["c"]] "a"  =  [["a"; "c"]]
\end{verbatim}
}

\pause

{\blue
\begin{alltt}
let rec extColoring m cols c =
    match cols with
    | []         -> [[c]]
    | col::cols' -> if canBeExtBy m col c
                    then (c::col)::cols'
                    else col::extColoring m cols' c;;
\end{alltt}
}


\bigskip

\pause
\begin{center}\em\redbrown
Function types, consistent use of symbols, and examples\\
make program easy to comprehend
\end{center}

\end{frame}




\begin{frame}[fragile]\frametitle{Functional decomposition (II)}

To color a neighbour relation:
\begin{itemize}
\item Get a list of countries from the neighbour relation.

\item Color these countries
\end{itemize}

\bigskip
\pause[2]
Get a list of countries {\redbrown without duplicates}:
{\blue
\begin{verbatim}
let addElem x ys = if isMember x ys then ys else x::ys;;

let rec countries = function
    | []           -> []
    | (c1,c2)::m -> addElem c1 (addElem c2 (countries m));;
\end{verbatim}
}

\pause[3]

Color a country list:
{\blue
\begin{verbatim}
let rec colCntrs m = function
    | []    -> []
    | c::cs -> extColoring m (colCntrs m cs) c;;
\end{verbatim}
}

\end{frame}


\begin{frame}[fragile]\frametitle{Functional composition (III)}

\begin{center}
The problem can now be solved by\\
\darkgreen combining {\redbrown well-understood pieces}
\end{center}

\pause
\bigskip
Create a coloring from a neighbour relation:
\begin{center}\blue
colMap:  map $\to$ coloring
\end{center}

\pause
\bigskip

{\blue
\begin{alltt}
let colMap m = colCntrs m (countries m);;

colMap exMap;;
\ett{val it : string list list = [["c"; "a"]; ["b"; "d"]]}
\end{alltt}
}

\end{frame}



\begin{frame}{On modelling and problem solving}

\begin{itemize}
\item Types are useful in the specification of concepts and
operations.

\item<2-> Conscious and consistent use of symbols enhances
readability.

\item<3->Examples may help understanding the problem and its
solution.

\item<4->Functional paradigm is powerful.
\begin{center}
Problem solving by
combination of well-understood pieces
\end{center}

\end{itemize}

\bigskip
\pause[5]

\begin{center}\darkgreen These points are not programming language
specific
\end{center}


\end{frame}


\end{document}

