% mrh 17/ 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}

\usepackage{tikz}

\input{macros}


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

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

\subtitle
{Collections: Sets and Maps} % (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 12/10/2012}% (optional)
%{Advanced Topics on Embedded Systems}

%\subject{Talks}
% This is only inserted into the PDF information catalog. Can be left
% out.



% If you have a file called "university-logo-filename.xxx", where xxx
% is a graphic format that can be processed by latex or pdflatex,
% resp., then you can add a logo as follows:

 \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}{Outline}
%  \tableofcontents
  % You might wish to add the option [pausesections]
%\end{frame}



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

Sets and Maps as abstract data types
\begin{itemize}

\item Useful in the modelling and solution of many problems

\item Many similarities with the list library

\end{itemize}

Recommendation: Use these libraries whenever it is appropriate.

\end{frame}


\begin{frame}[fragile]\frametitle{The set concept (1)}

A {\em set} (in mathematics) is a collection of element like
\[\blue
\{ \mathrm{Bob}, \mathrm{Bill}, \mathrm{Ben} \}, \{ 1, 3, 5, 7, 9\}, \Nat, \text{and}\ \Real
\]

\begin{itemize}
\item the sequence in which elements are enumerated is of no concern, and
\item repetitions among members of a set is of no concern either
\end{itemize}

\medskip
\pause

It is possible to decide whether a given value is in the set.
\[\blue \mathrm{Alice} \not \in \{ \mathrm{Bob}, \mathrm{Bill}, \mathrm{Ben} \}  \qquad \text{and} \qquad 7 \in \{ 1, 3, 5, 7, 9\} \]

\medskip
\pause

The empty set containing no element is written $\{ \}$ or $\emptyset$.


\end{frame}

\begin{frame}[fragile]\frametitle{The sets concept (2)}

A set $A$ is a {\em subset} of a set $B$, written $A \subseteq B$, if all the elements of $A$ are also elements of $B$, for example
\[\blue  \{ \mathrm{Ben}, \mathrm{Bob} \}  \subseteq \{ \mathrm{Bob}, \mathrm{Bill}, \mathrm{Ben} \}
\qquad \text{and} \qquad \{ 1, 3, 5, 7, 9\} \subseteq \Nat \]

\medskip
\pause

Two sets $A$ and $B$ are equal, if they are both subsets of each other:
\[\blue A=B \qquad \text{if and only if} \qquad A \subseteq B \text{ and } B \subseteq A   \]
i.e.\ two sets are equal if they contain exactly the same elements.

\medskip
\pause

The subset of a set $A$ which consists of those elements satisfying a predicate $p$ can be expressed using a {\em set-comprehension}:
\[
\{\blue x \in A\ |\ p(x) \}
\]

\medskip

For example:
\[\blue  \{ 1, 3, 5, 7, 9\} = \{ x \in \Nat\ |\ \mathrm{odd}(x) \text{ and } x < 11 \} \]

\end{frame}

\begin{frame}[fragile]\frametitle{The set concept (3)}

Some standard operations on sets:
%{\em union}: $A \cup B$, {\em intersection} $A \cap B$ and {\em difference} $A \setminus B$:
\[\blue
\begin{array}{lcll}
A \cup B      & = & \{ x\ |\ x \in A \text{ or } x \in B \}  & \text{union}\\
A \cap B      & = & \{ x\ |\ x \in A \text{ and } x \in B \} \qquad & \text{intersection} \\
A \setminus B & = & \{ x\in A\ |\ x \not \in B \}            & \text{difference}
\end{array}
\]


\begin{figure}
\def\firstcircle{(180:0.65cm) circle(0.9cm)}
\def\secondcircle{(0:0.65cm) circle(0.9cm)}
\begin{tabular}{ccc}
\begin{tikzpicture}
  \begin{scope}
    \fill[gray] \firstcircle;
    \fill[gray] \secondcircle;
  \end{scope}
\draw \firstcircle node[text=black] {$A$};
\draw \secondcircle node [text=black] {$B$};
\end{tikzpicture}
 &
\begin{tikzpicture}
  \begin{scope}
    \clip \firstcircle;
    \fill[gray] \secondcircle;
  \end{scope}
\draw \firstcircle node[text=black] {$A$};
\draw \secondcircle node [text=black] {$B$};
\end{tikzpicture} &
\begin{tikzpicture}
  \begin{scope}
    \fill[gray] \firstcircle;
    \fill[white] \secondcircle;
  \end{scope}
\draw \firstcircle node[text=black] {$A$};
\draw \secondcircle node [text=black] {$B$};
\end{tikzpicture}\\
(a) $A \cup B$ & (b) $A \cap B$ & (c) $A \setminus B$
\end{tabular}

\caption{Venn diagrams for (a) union, (b) intersection and (c) difference}
\label{fig:venn.diagram}
\end{figure}

\pause

For example
\begin{eqnarray*}
\{ \mathrm{Bob}, \mathrm{Bill}, \mathrm{Ben} \} \cup \{ \mathrm{Alice}, \mathrm{Bill}, \mathrm{Ann} \} & = & \{ \mathrm{Alice}, \mathrm{Ann}, \mathrm{Bob}, \mathrm{Bill}, \mathrm{Ben} \} \\
\{ \mathrm{Bob}, \mathrm{Bill}, \mathrm{Ben} \} \cap \{ \mathrm{Alice}, \mathrm{Bill}, \mathrm{Ann} \} & = & \{ \mathrm{Bill} \} \\
\{ \mathrm{Bob}, \mathrm{Bill}, \mathrm{Ben} \} \setminus \{ \mathrm{Alice}, \mathrm{Bill}, \mathrm{Ann} \} & = & \{ \mathrm{Bob}, \mathrm{Ben} \}
\end{eqnarray*}
\end{frame}


\begin{frame}[fragile]\frametitle{Abstract Data Types}

An abstract Data Type: A type together with a collection of operations, where
\begin{itemize}

\item the representation of values is hidden.

\end{itemize}


\bigskip
\pause

An abstract data type for sets must have:
\begin{itemize}

\item Operations to generate sets from the elements. Why?

\item Operations to extract the elements of a set. Why?

\item Standard operations on sets.

\end{itemize}

\end{frame}


\begin{frame}[fragile]\frametitle{Sets in F\#}

The \verb-Set- library of F\# supports finite sets. An efficient implementation is based on a balanced binary tree.


\medskip

Examples:
\begin{alltt}\blue
set ["Bob"; "Bill"; "Ben"];;
\ett{val it : Set<string> = set ["Ben"; "Bill"; "Bob"]}

set [3; 1; 9; 5; 7; 9; 1];;
\ett{val it : Set<int> = set [1; 3; 5; 7; 9]}
\end{alltt}

\medskip

Equality of two sets is tested in the usual manner:
\begin{alltt}\blue
set["Bob";"Bill";"Ben"] = set["Bill";"Ben";"Bill";"Bob"];;
\ett{val it : bool = true}
\end{alltt}

\medskip
Sets are order on the basis of a lexicographical ordering:
\begin{alltt}\blue
compare (set ["Ann";"Jane"]) (set ["Bill";"Ben";"Bob"]);;
\ett{val it : int = -1}
\end{alltt}

\end{frame}

\begin{frame}[fragile]\frametitle{Selected operations (1)}


\begin{itemize}
\item \verb!ofList: 'a list -> Set<'a>!, \\
where %\\ \qquad
$\verb!ofList!\ [a_0; \ldots; a_{n-1} ] =  \{a_0; \ldots; a_{n-1} \}$

\item \verb!toList: Set<'a> -> 'a list!, \\
where  $\verb!toList!\ \{a_0, \ldots, a_{n-1} \} =  [a_0; \ldots; a_{n-1} ]$

\item \verb!add: 'a -> Set<'a> -> Set<'a>!,\\
where % \\ \qquad
$\verb!add!\ a\ A = \{ a \} \cup A$

\item \verb!remove: 'a -> Set<'a> -> Set<'a>!,\\
where %\\ \qquad
$\verb!remove!\ a\ A = A \setminus \{a\}$

\item \verb!contains: 'a -> Set<'a> -> bool!,\\ where %\\ \qquad
$\verb!contains!\ a\ A = a \in A$
%\verb!isSubset: Set<'a> -> Set<'a> -> bool!, where %\\ \qquad
%$\verb!isSubset!\ A\ B = A \subseteq B$\\

\item \verb!minElement: Set<'a> -> 'a)!  \\
where $\verb!minElement!\ \{a_0, a_1, \ldots, a_{n-2}, a_{n-1}\} = a_0$ when $n>0$\\
%\verb!maxElement: Set<'a> -> 'a)!  \\
%\qquad $\verb!minElement!\ \{a_0, a_1, \ldots, a_{n-2}, a_{n-1}\} = a_{n-1}$ when $n>0$\\
%\verb!count: Set<'a> -> int)!  \\
% \qquad $\verb!count!\ \{a_0, a_1, \ldots, a_{n-2}, a_{n-1}\} = n$\\

\end{itemize}

\medskip
\pause

Notice that minElement is well-defined due to the ordering:
\begin{alltt}\blue
Set.minElement (Set.ofList ["Bob"; "Bill"; "Ben"]);;
\ett{val it : string = "Ben"}
\end{alltt}


\end{frame}


\begin{frame}[fragile]\frametitle{Selected operations (2)}

\begin{itemize}

\item \verb!union: Set<'a> -> Set<'a> -> Set<'a>!,\\ where %\\ \qquad
$\verb!union!\ A\ B = A \cup B$

\item \verb!intersect: Set<'a> -> Set<'a> -> Set<'a>!,\\ where %\\\qquad
$\verb!intersect!\ A\ B = A \cap B$

\item \verb!difference: Set<'a> -> Set<'a> -> Set<'a>!,\\ where %\\ \qquad
$\verb!difference!\ A\ B = A \setminus B$

%\verb!filter: ('a -> bool) -> Set<'a> -> bool!, where % \\ \qquad
%$\verb!filter!\ p\ A = \{ x \in A\ | p(x)\}$\\

\item \verb!exists: ('a -> bool) -> Set<'a> -> bool!,\\ where % \\ \qquad
$\verb!exists!\ p\ A = \exists x \in A. p(x)$

\item \verb!forall: ('a -> bool) -> Set<'a> -> bool!,\\ where % \\ \qquad
$\verb!forall!\ p\ A = \forall x \in A. p(x)$

%\verb!map: ('a -> 'b) -> Set<'a> -> Set<'b>!, where % \\ \qquad
%$\verb!map!\ f\ A = \{ f(x) | x \in A\}$\\

\item \verb!fold: ('a -> 'b -> 'a) -> 'a -> Set<'b> -> 'a!,\\ where
\[\begin{array}{ll}
\verb!fold!\ f\ a\ \{b_0, b_1, \ldots, b_{n-2}, b_{n-1}\}\\
= f(f(f( \cdots f(f(a, b_0),b_1), \ldots),b_{n-2}), b_{n-1})
\end{array}
\]

\end{itemize}

\pause

These work similar to their List siblings, e.g.
\[\blue
\begin{array}{c}
\verb!Set.fold (-) 0 (set [1; 2; 3])! = ((0-1) -2)-3 = -6
\end{array}
\]
where the ordering is exploited.

\end{frame}


\begin{frame}[fragile]\frametitle{Example: Map Coloring (1)}

Maps and colors are modelled in a more natural way using sets:
\begin{alltt}\blue
type country  = string;;
type map      = Set<country*country>;;
type color    = Set<country>;;
type coloring = Set<color>;;
\end{alltt}

\medskip

\hfill WHY?

\medskip
\pause

Two countries $c_1, c_2$ are neighbors in a map $m$,\\
\qquad if either $(c_1,c_2) \in m$ or $(c_2,c_1) \in m$:
\begin{alltt}\blue
let areNb c1 c2 m =
   Set.contains (c1,c2) m || Set.contains (c2,c1) m;;
\end{alltt}

\medskip
\pause

Color $\mathit{col}$ and be extended by a country $c$ given map $m$,\\
\qquad if for every country $c'$ in  $\mathit{col}$: $c$ and $c'$ are not neighbours in $m$
\begin{alltt}\blue
let canBeExtBy m col c =
   Set.forall (fun c' -> not (areNb c' c m)) col;;
\end{alltt}
\end{frame}

\begin{frame}[fragile]\frametitle{Example: Map Coloring (2)}

The function
\begin{alltt}\blue
extColoring: map -> coloring -> country -> coloring
\end{alltt}
is declared as a recursive function over the coloring: \\[2mm]
\hfill WHY not use a fold function?

\pause

\begin{alltt}\blue
let rec extColoring m cols c =
   if Set.isEmpty cols
   then Set.singleton (Set.singleton c)
   else let col = Set.minElement cols
        let cols' = Set.remove col cols
        if canBeExtBy m col c
        then Set.add (Set.add c col) cols'
        else Set.add col (extColoring m cols' c);;
\end{alltt}

Notice similarity to a list recursion:
\begin{itemize}
\item base case [] corresponds to the empty set

\item for a recursive case x::xs, the head x corresponds to the minimal element col and the tail xs corresponds to the "rests" set cols'
\end{itemize}
\pause
The list-based version is more efficient (why?) and more readable.
\end{frame}

\begin{frame}[fragile]\frametitle{Example: Map Coloring (3)}

A set of countries is obtained from a map by the function:
\begin{alltt}\blue
countries: map -> Set<country>
\end{alltt}
that is based on repeated insertion of the countries into a set:
\begin{alltt}\blue
let countries m =
   Set.fold
      (fun set (c1,c2) -> Set.add c1 (Set.add c2 set))
      Set.empty
      m;;
\end{alltt}

\medskip
\pause

The function
\begin{alltt}\blue
colCntrs: map -> Set<country> -> coloring
\end{alltt}
is based on repeated insertion of countries in colorings using the \verb-extColoring- function:
\begin{alltt}\blue
let colCntrs m cs = Set.fold (extColoring m) Set.empty cs;;
\end{alltt}
\end{frame}

\begin{frame}[fragile]\frametitle{Example: Map Coloring (4)}
The function that creates a coloring from a map is declared using functional composition:

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

let exMap = Set.ofList [("a","b"); ("c","d"); ("d","a")];;

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

\end{frame}

\begin{frame}[fragile]\frametitle{The map concept}

A {\em map\/} from a set $A$ to a set $B$ is a {\em finite\/}
subset $A'$ of $A$ together with a {\em function\/} $m$ defined on $A'$: $\blue m: A' \rightarrow B$.

The set $A'$ is called the {\em domain} of $m$:  ${\rm dom}\, m = A'$.

\medskip

A map $m$ can be described in a tabular form:
\[\blue
\begin{array}{l|l}
a_0 & b_0 \\
\hline
a_1 & b_1 \\
\hline
  & \\
\multicolumn{2}{c}{\vdots} \\
  & \\
\hline
a_{n-1} & b_{n-1} \\
\end{array}
\]
%where
%$m(a_0) = b_0, m(a_1) = b_1, \ldots, m(a_{n-1}) = b_{n-1}$
\medskip

\begin{itemize}
\item An element $a_i$ in the set $A'$ is called a \textit{key}

\item  A pair $(a_i,b_i)$ is called an \textit{entry}, and

\item $b_i$ is called the
\textit{value} for the key $a_i$.

\end{itemize}

\medskip

We denote the sets of entries of a map as follows:
\[\blue
\mathrm{entriesOf}(m) = \{ (a_0,b_0), \ldots, (a_{n-1},b_{n-1}) \}
\]


\end{frame}

\begin{frame}[fragile]\frametitle{Selected map operations in F\#}

\begin{itemize}

\item \verb!ofList: ('a*'b) list -> Map<'a,'b>!\\
%where \\
$\verb!ofList!\ [(a_0,b_0); \ldots; (a_{n-1},b_{n-1})] = m$

%\verb!toList: Map<'a,'b> -> ('a*'b) list!, where \\
%\qquad $\verb!toList!\ m = [(a_0,b_0); \ldots;
%                                            (a_{n-1},b_{n-1})]$\\

\item \verb!add: 'a -> 'b -> Map<'a,'b> -> Map<'a,'b>!\\ %where %\\
$\verb!add!\ a\ b\ m = m'$, where $m'$ is obtained $m$ by overriding $m$ with the entry $(a,b)$
%\verb!containsKey: 'a -> Map<'a,'b> -> bool!, where $\verb!containsKey!\ a\ m = a \in \mathrm{dom}\ m$\\


\item \verb!find: 'a -> Map<'a,'b> -> 'b!\\
$\verb!find!\ a\ m = m(a)$, if $a \in \mathrm{dom}\ m$;\\
otherwise an exception is raised

\item \verb!tryFind: 'a -> Map<'a,'b> -> 'b option!\\
$\verb!tryFind!\ a\ m = \mathtt{Some}\ (m(a))$, if $a \in \mathrm{dom}\ m$; \texttt{None} otherwise

\item \verb!foldBack: ('a->'b->'c->'c) -> Map<'a,'b> -> 'c -> 'c!\\
$\verb!foldBack!\ f\ m\ c= f\, a_0\, b_0\, (f\, a_1\, b_1\, (f \ldots (f\, a_{n-1}\, b_{n-1}\, c) \cdots ))$
\end{itemize}

\end{frame}


\begin{frame}[fragile]\frametitle{A few examples}

\begin{alltt}\blue
let reg1 = Map.ofList [("a1",("cheese",25));
                       ("a2",("herring",4));
                       ("a3",("soft drink",5))];;
\ett{val reg1 : Map<string,(string * int)> =}
\ett{  map [("a1", ("cheese", 25)); ("a2", ("herring", 4)); }
\ett{       ("a3", ("soft drink", 5))]}
\end{alltt}

\medskip

An entry can be added to a map using \verb!add! and the value for a key in a map is retrieved using either \verb!find! or \verb!tryFind!:
\begin{alltt}\blue
let reg2 = Map.add "a4" ("bread", 6) reg1;;
\ett{val reg2 : Map<string,(string * int)> =}
\ett{  map [("a1", ("cheese", 25)); ("a2", ("herring", 4));}
\ett{       ("a3", ("soft drink", 5)); ("a4", ("bread", 6))]}

Map.find "a2" reg1;;
\ett{val it : string * int = ("herring", 4)}

Map.tryFind "a2" reg1;;
\ett{val it : (string * int) option = Some ("herring", 4)}
\end{alltt}

\end{frame}

\begin{frame}[fragile]\frametitle{An example using Map.foldBack}

We can extract the list of article codes and prices for a given register using the fold functions for maps:
\begin{alltt}\blue
let reg1 = Map.ofList [("a1",("cheese",25));
                       ("a2",("herring",4));
                       ("a3",("soft drink",5))];;

Map.foldBack (fun ac (_,p) cps -> (ac,p)::cps) reg1 [];;
\ett{val it : (string * int) list =}
\ett{    [("a1", 25); ("a2", 4); ("a3", 5)]}
\end{alltt}

\medskip

This and other higher-order functions are similar to their List and Set siblings.


\end{frame}

\begin{frame}[fragile]\frametitle{Example: Cash register (1)}

\begin{alltt}\blue
type articleCode = string;;
type articleName = string;;
type noPieces    = int;;
type price       = int;;

type info        = noPieces * articleName * price;;
type infoseq     = info list;;
type bill        = infoseq * price;;
\end{alltt}

\medskip
\pause

The natural model of a register is using a map:
\begin{alltt}\blue
type register    = Map<articleCode, articleName*price>;;
\end{alltt}
since an article code is {\em a unique identification} of an article.

\medskip

First version:
\begin{alltt}\blue
type item        = noPieces * articleCode;;
type purchase    = item list;;
\end{alltt}

\end{frame}

\begin{frame}[fragile]\frametitle{Example: Cash register (1) - a recursive program}

\begin{alltt}\blue
exception FindArticle;;

(* makebill: register -> purchase -> bill *)
let rec makeBill reg = function
    | []           -> ([],0)
    | (np,ac)::pur ->
        match Map.tryFind ac reg with
        | None              -> raise FindArticle
        | Some(aname,aprice) ->
            let tprice         = np*aprice
            let (infos,sumbill) = makeBill reg pur
            ((np,aname,tprice)::infos, tprice+sumbill);;

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

\pause

\begin{itemize}

\item the lookup in the register is managed by a \verb!Map.tryFind!

\end{itemize}

\end{frame}

\begin{frame}[fragile]\frametitle{Example: Cash register (2) - using List.foldBack}

\begin{alltt}\blue
let makeBill' reg pur =
   let f (np,ac) (infos,billprice)
          = let (aname, aprice) = Map.find ac reg
            let tprice          = np*aprice
            ((np,aname,tprice)::infos, tprice+billprice)
   List.foldBack f pur ([],0);;

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


\begin{itemize}

\item<2-> the recursion is handled by List.foldBack

\item<3-> the exception is handled by \verb!Map.find!

\end{itemize}

\end{frame}

\begin{frame}[fragile]\frametitle{Example: Cash register (2) - using maps for purchases}

The purchase: 3 herrings, one piece of cheese, and 2 herrings, is the
same as a purchase of one piece of cheese and 5 herrings.

\medskip
\pause

A purchase associated number of pieces with article codes:
\begin{alltt}\blue
type purchase    = Map<articleCode,noPieces>;;
\end{alltt}

\pause

A bill is produced by folding a function over a map-purchase:
\begin{alltt}\blue
let makeBill'' reg pur =
   let f ac np (infos,billprice)
          = let (aname, aprice) = Map.find ac reg
            let tprice          = np*aprice
            ((np,aname,tprice)::infos, tprice+billprice)
   Map.foldBack f pur ([],0);;

let purMap = Map.ofList [("a2",3); ("a1",1)];;
\ett{val purMap : Map<string,int> = map [("a1", 1); ("a2", 3)]}

makeBill'' reg1 purMap;;
\ett{val it = ([(1, "cheese", 25); (3, "herring", 12)], 37)}
\end{alltt}

\end{frame}

\begin{frame}{Summary}

\begin{itemize}
\item The concepts of sets and maps.

\item Fundamental operations on sets and maps.

\item Applications of sets and maps.
\end{itemize}


\end{frame}

\end{document}
