% 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}

\input{macros}


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

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

\subtitle
{Finite Trees (I)} % (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 11/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}{Overview}

Finite Trees
\begin{itemize}

\item Algebraic Datatypes.

\begin{itemize}

\item Non-recursive type declarations: {\redbrown Disjoint
union} (Lecture 4)


\item Recursive type declarations: {\redbrown Finite trees}

\end{itemize}

\item<2->Recursions following the structure of trees

%\item<2->Use of Case expressions

%\item<2->Selected predefined types and functions

\item<3->{Illustrative examples:
\begin{itemize}
\item Search trees

\item Expression trees

\item File systems

\item $\darkgreen \ldots$
\end{itemize}}

\item<4-> Mutual recursion, layered pattern, polymorphic type declarations

\end{itemize}
\end{frame}


\begin{frame}[fragile]\frametitle{Finite trees}

A {\em\blue finite
  tree\/} is a value which may contain a subcomponent of the same
type.

\bigskip
\pause
Example: A {\redbrown\em binary search tree}

\medskip

\begin{center}
\setlength{\unitlength}{2500sp}%
%\setlength{\unitlength}{3947sp}%
%
\begingroup\makeatletter\ifx\SetFigFont\undefined%
\gdef\SetFigFont#1#2#3#4#5{%
  \reset@font\fontsize{#1}{#2pt}%
  \fontfamily{#3}\fontseries{#4}\fontshape{#5}%
  \selectfont}%
\fi\endgroup%
\begin{picture}(7287,2835)(1126,-2761)
\thinlines \put(4801,-61){\line( 0,-1){675}}
%\put(4801,-61){\line( 5,-2){1810.345}}
\put(4801,-61){\line( 5,-2){1700.000}}
%\put(4801,-61){\makebox(1.6667,11.6667){\SetFigFont{5}{6}{\rmdefault}{\mddefault}{\updefault}.}}
%\put(4801,-61){\line(-5,-2){1810.345}}
\put(4801,-61){\line(-5,-2){1700.000}}

%\put(3001,-961){\line( 0,-1){750}}
\put(3001,-961){\line( 0,-1){710}}

%\put(3001,-961){\line(-5,-3){1213.235}}
\put(3001,-961){\line(-5,-3){1100.000}}

%\put(3001,-961){\line( 5,-3){1213.235}}
\put(3001,-961){\line( 5,-3){1100.000}}



\put(1801,-1861){\line(-4,-5){600}} \put(1801,-1936){\line(
0,-1){600}} \put(1801,-1861){\line( 4,-5){600}}

%\put(6601,-961){\line(-5,-3){1180.147}}
\put(6601,-961){\line(-5,-3){1100.000}}

\put(6601,-961){\line( 0,-1){675}}

%\put(6601,-961){\line( 5,-3){1213.235}}
\put(6601,-961){\line( 5,-3){1100.000}}

\put(5401,-1861){\line(-5,-6){577.869}} \put(5401,-1861){\line(
0,-1){675}} \put(5401,-1861){\line( 4,-5){600}}
\put(7801,-1861){\line(-5,-6){577.869}} \put(7801,-1861){\line(
0,-1){750}} \put(7801,-1861){\line( 4,-5){600}}

\put(4650,-35){\makebox(0,0)[lb]{{\tt Br}}}

%\put(2926,-961){\makebox(0,0)[lb]{Br}}
%\put(6526,-961){\makebox(0,0)[lb]{Br}}
\put(2926,-930){\makebox(0,0)[lb]{{\tt Br}}}
\put(6526,-930){\makebox(0,0)[lb]{{\tt Br}}}

\put(1726,-1800){\makebox(0,0)[lb]{{\tt Br}}}
\put(4126,-1800){\makebox(0,0)[lb]{{\tt Lf}}}
\put(5326,-1800){\makebox(0,0)[lb]{{\tt Br}}}
\put(7726,-1800){\makebox(0,0)[lb]{{\tt Br}}}

%
\put(1126,-2800){\makebox(0,0)[lb]{{\tt Lf}}}
\put(1726,-2800){\makebox(0,0)[lb]{2}}
\put(2326,-2800){\makebox(0,0)[lb]{{\tt Lf}}}

\put(2926,-1861){\makebox(0,0)[lb]{7}}

\put(4726,-2800){\makebox(0,0)[lb]{{\tt Lf}}}
\put(5251,-2800){\makebox(0,0)[lb]{13}}
\put(5926,-2800){\makebox(0,0)[lb]{{\tt Lf}}}
\put(7126,-2800){\makebox(0,0)[lb]{{\tt Lf}}}
\put(7651,-2800){\makebox(0,0)[lb]{25}}
\put(8326,-2800){\makebox(0,0)[lb]{{\tt Lf}}}

\put(6466,-1861){\makebox(0,0)[lb]{21}}
\put(4726,-961){\makebox(0,0)[lb]{9}}

%\put(4726,-61){\makebox(0,0)[lb]{ \smash{\SetFigFont{10}{14.4}{rm}Br}}}
%\put(2926,-961){\makebox(0,0)[lb]{Br}}
%\put(6526,-961){\makebox(0,0)[lb]{Br}}
%\put(1726,-1861){\makebox(0,0)[lb]{Br}}
%\put(4126,-1861){\makebox(0,0)[lb]{Lf}}
%\put(5326,-1861){\makebox(0,0)[lb]{Br}}
%\put(7726,-1861){\makebox(0,0)[lb]{Br}}
%\put(1126,-2761){\makebox(0,0)[lb]{Lf}}
%\put(1726,-2761){\makebox(0,0)[lb]{2}}
%\put(2326,-2761){\makebox(0,0)[lb]{Lf}}
%\put(2926,-1861){\makebox(0,0)[lb]{7}}
%\put(4726,-2761){\makebox(0,0)[lb]{Lf}}
%\put(5251,-2761){\makebox(0,0)[lb]{13}}
%\put(5926,-2761){\makebox(0,0)[lb]{Lf}}
%\put(7126,-2761){\makebox(0,0)[lb]{Lf}}
%\put(7651,-2761){\makebox(0,0)[lb]{25}}
%\put(8326,-2761){\makebox(0,0)[lb]{Lf}}
%\put(6526,-1861){\makebox(0,0)[lb]{21}}
%\put(4726,-961){\makebox(0,0)[lb]{9}}
\end{picture}

\end{center}

\bigskip

{\redbrown Condition:} for every node containing the value $x$:
every value in the left subtree is smaller then $x$, and every
value in the right subtree is greater than $x$.

\end{frame}



\begin{frame}[fragile]\frametitle{Example: Binary Trees}

A {\em\blue recursive datatype} is used to represent values which
are trees.

\medskip

\begin{alltt}
type Tree = Lf
          | Br of Tree*int*Tree;;

Lf;;
\ett{\redbrown{val it : Tree = Lf}}

Br;;
\ett{\redbrown{val it : Tree * int * Tree -> Tree = <fun:clo@4>}}

\end{alltt}

\medskip
\pause

The two parts in the declaration are {\redbrown rules} for
generating trees:
\begin{itemize}
\item \mbox{}{\tt\blue Lf} is a tree \item if $\blue t_1, t_2$ are
trees, $\blue n$ is an integer, then ${\blue {\tt Br}(t_1, n,
t_2)}$ is a tree.
\end{itemize}
\medskip

\pause

The tree from the previous slide is denoted by:
\begin{alltt}
Br(Br(Br(Lf,2,Lf),7,Lf),
   9,
   Br(Br(Lf,13,Lf),21,Br(Lf,25,Lf)))
\end{alltt}

\end{frame}


\begin{frame}[fragile]\frametitle{Binary search trees: Insertion}


\begin{itemize}
\item Recursion on the structure of trees

\item Constructors {\normalsize\blue\tt Lf} and
{\normalsize\blue\tt Br} are used in {\redbrown patterns}

\item The search tree condition is an {\redbrown invariant} for
\texttt{\blue \normalsize insert}

\end{itemize}

\pause

\begin{alltt}
let rec insert i = function
  | Lf                ->  Br(Lf,i,Lf)
  |{\redbrown Br(t1,j,t2) as tr} ->
      match compare i j with
      | 0           -> tr
      | n when n<0  -> Br(insert i t1 , j, t2)
      | _           -> Br(t1,j, insert i t2);;
\ett{val insert : int -> Tree -> Tree}
\end{alltt}

\pause

Example:
\begin{alltt}
let t1 = Br(Lf, 3, Br(Lf, 5, Lf));;
let t2 = insert 4 t1;;
\ett{val t2 : Tree = Br (Lf,3,Br (Br (Lf,4,Lf),5,Lf))}
\end{alltt}

\end{frame}



\begin{frame}[fragile]\frametitle{Binary search trees: {\Large\tt\redbrown member} and
    {\Large\tt\redbrown inOrder} traversal}

\begin{alltt}
let rec memberOf  i = function
  | Lf          -> false
  | Br(t1,j,t2) -> match compare i j with
                   | 0   -> true
                   | n when n<0 -> memberOf i t1
                   | _          -> memberOf i t2;;
\ett{val memberOf : int -> Tree -> bool}
\end{alltt}

\medskip
\pause

{\blue In-order traversal}

\medskip

\begin{alltt}
let rec inOrder = function
  | Lf          -> []
  | Br(t1,j,t2) -> inOrder t1 @ [j] @ inOrder t2;;

\ett{val toList : Tree -> int list}
\end{alltt}

\medskip
\pause

{\blue gives a sorted list}

\medskip

\begin{alltt}
inOrder(Br(Br(Lf,1,Lf), 3, Br(Br(Lf,4,Lf), 5, Lf)));;
\ett{val it : int list = [1; 3; 4; 5]}
\end{alltt}

\end{frame}



\begin{frame}[fragile]\frametitle{Deletions in search trees}

Delete {\redbrown minimal element} in a search tree: \texttt{\blue
Tree -> int * Tree}

\begin{alltt}
let rec delMin = function
  | Br(Lf,i,t2) -> (i,t2)
  | Br(t1,i,t2) -> let (m,t1') = delMin t1
                   (m, Br(t1',i,t2));;
\end{alltt}

\pause

Delete {\redbrown element} in a search tree: \texttt{\blue int ->
Tree -> Tree}
\begin{verbatim}
let rec delete j = function
  | Lf          -> Lf
  | Br(t1,i,t2) ->
       match compare i j with
       | n when n<0 -> Br(t1,i,delete j t2)
       | n when n>0 -> Br(delete j t1,i,t2)
       | _          ->
            match t2 with
            | Lf -> t1
            | _  -> let (m,t2') = delMin t2
                    Br(t1,m,t2');;
\end{verbatim}
\end{frame}

\begin{frame}[fragile]\frametitle{Parameterize type declarations}

The programs on search trees just requires an ordering on elements -- they no not need to be integers.

\bigskip
\pause

A polymorphic tree type is declared as follows:
\begin{alltt}\blue
type Tree<'a> = Lf | Br of Tree<'a> * 'a * Tree<'a>;;
\end{alltt}

\medskip
\pause

Program texts are unchanged (though {\redbrown polymorphic} now), for example
\begin{alltt}
let rec insert i = function
       ....
  | Br(t1,j,t2) as tr -> match{\redbrown compare} i j with
       .... ;;
\ett{val insert: 'a -> Tree<'a> -> Tree<'a> when{\redbrown 'a: comparison}}
\pause
let ti = insert 4  (Br(Lf, 3, Br(Lf, 5, Lf)));;
\ett{val ti : Tree<int> = Br (Lf,3,Br (Br (Lf,4,Lf),5,Lf))}
\pause
let ts = insert "4" (Br(Lf, "3", Br(Lf, "5", Lf)));;
\ett{val ts : Tree<string>}
\ett{       = Br (Lf,"3",Br (Br (Lf,"4",Lf),"5",Lf))}
\end{alltt}

\end{frame}

\begin{frame}[fragile]\frametitle{Higher-order functions for tree traversals}

For example
\begin{alltt}\blue
let rec inFoldBack f t e =
    match t with
    | Lf          -> e
    | Br(t1,x,t2) -> let er = inFoldBack f t2 e
                     inFoldBack f t1 (f x er);;
\ett{val inFoldBack: ('a -> 'b -> 'b) -> Tree<'a> -> 'b -> 'b}
\end{alltt}
satisfies
\[\redbrown
\mathtt{inFoldBack}\ f\ t\ e\ = \mathtt{List.foldBack}\ f\ (\mathtt{inOrder}\ t)\ e
\]

\pause
\medskip

It traverses the tree without building the list- For example:
\begin{alltt}\blue
let ta = Br(Br(Br(Lf,-3,Lf),0,Br(Lf,2,Lf)),5,Br(Lf,7,Lf));;

inOrder ta;;
\ett{val it : int list = [-3; 0; 2; 5; 7]}

inFoldBack (-) ta 0;;
\ett{val it : int = 1}
\end{alltt}

\end{frame}

\begin{frame}[fragile]\frametitle{Example: Expression Trees}
{\blue
\begin{alltt}
type Fexpr =
  | Const of float
  | X
  | Add of Fexpr * Fexpr
  | Sub of Fexpr * Fexpr
  | Mul of Fexpr * Fexpr
  | Div of Fexpr * Fexpr;;
\end{alltt}}

\pause
\bigskip

Defines 6 {\redbrown constructors}:
\begin{itemize}
\item \verb!Const: float -> Fexpr!

\item \verb!X : Fexpr!

\item \verb!Add: Fexpr * Fexpr -> Fexpr!

\item \verb!Sub: Fexpr * Fexpr -> Fexpr!

\item \verb!Mul: Fexpr * Fexpr -> Fexpr!

\item \verb!Div: Fexpr * Fexpr -> Fexpr!
\end{itemize}

\end{frame}



\begin{frame}[fragile]\frametitle{Symbolic Differentiation\ \texttt{\redbrown D: Fexpr -> Fexpr}}

A classic example in functional programming:

{\blue
\begin{alltt}
let rec D = function
  | Const _      -> Const 0.0
  | X            -> Const 1.0
  | Add(fe1,fe2) -> Add(D fe1,D fe2)
  | Sub(fe1,fe2) -> Sub(D fe1,D fe2)
  | Mul(fe1,fe2) -> Add(Mul(D fe1,fe2),Mul(fe1,D fe2))
  | Div(fe1,fe2) -> Div(
                       Sub(Mul(D fe1,fe2),Mul(fe1,D fe2)),
                       Mul(fe2,fe2));;
\end{alltt}
}
Notice the direct correspondence with the rules of differentiation.

\bigskip
\pause

Can be tried out directly, as tree are "just" values, for example:
\begin{alltt}
D(Add(Mul(Const 3.0, X), Mul(X, X)));;
\ett{val it : Fexpr =}
\ett{  Add}
\ett{    (Add (Mul (Const 0.0,X),Mul (Const 3.0,Const 1.0)),}
\ett{     Add (Mul (Const 1.0,X),Mul (X,Const 1.0)))}
\end{alltt}
\end{frame}


\begin{frame}[fragile]\frametitle{Expressions: Computation of values}

Given a value (a float) for \texttt{X}, then every expression denote a float.

\medskip

{\blue
\begin{alltt}
    compute : float -> Fexpr -> float
\end{alltt}
}
\medskip
\pause

{\blue
\begin{alltt}
let rec compute x = function
  | Const r       -> r
  | X             -> x
  | Add(fe1,fe2)  -> compute x fe1 + compute x fe2
  | Sub(fe1,fe2)  -> compute x fe1 - compute x fe2
  | Mul(fe1,fe2) -> compute x fe1 * compute x fe2
  | Div(fe1,fe2)  -> compute x fe1 / compute x fe2;;


\end{alltt}
}
\bigskip
\pause

Example:

\begin{alltt}
compute 4.0 (Mul(X, Add(Const 2.0, X)));;
\ett{val it : float = 24.0}
\end{alltt}

\end{frame}




\begin{frame}[fragile]\frametitle{Mutual recursion. Example: File system}

\begin{center}
\setlength{\unitlength}{0.9mm}
%\setlength{\unitlength}{1mm}
\begin{picture}(60,70)
\put(30,65){\makebox(0,0){$d_1$}}

\put(30,60){\line(0,-1){10}}
\put(0,50){\line(1,0){60}}

\put(0,50){\line(0,-1){5}}
\put(60,50){\line(0,-1){5}}

\put(6,45){\makebox(0,0){$a_1$}}
\put(22,45){\makebox(0,0){$d_2$}}
\put(38,45){\makebox(0,0){$a_4$}}
\put(54,45){\makebox(0,0){$d_3$}}

\put(22,40){\line(0,-1){10}}
\put(54,40){\line(0,-1){10}}

\put(14,30){\line(1,0){16}}
\put(50,30){\line(1,0){8}}
\put(14,30){\line(0,-1){5}}
\put(30,30){\line(0,-1){5}}
\put(50,30){\line(0,-1){5}}
\put(58,30){\line(0,-1){5}}

\put(54,25){\makebox(0,0){$a_5$}}
\put(18,25){\makebox(0,0){$a_2$}}
\put(26,25){\makebox(0,0){$d_3$}}

\put(26,20){\line(0,-1){10}}
\put(22,10){\line(1,0){8}}
\put(22,10){\line(0,-1){5}}
\put(30,10){\line(0,-1){5}}
\put(26,5){\makebox(0,0){$a_3$}}
\end{picture}
\end{center}

\begin{itemize}
\item A {\darkgreen file system} is a list of {\redbrown elements}
\item an {\redbrown element} is a file or a directory, which is a named {\darkgreen file system}
\end{itemize}
\end{frame}



\begin{frame}[fragile]\frametitle{Mutually recursive type declarations}

\begin{itemize} \item are combined using {\redbrown and}
\end{itemize}

\bigskip

\begin{alltt}
type FileSys = Element list
{\redbrown{and}} Element =
  | File of string
  | Dir of string * FileSys
\end{alltt}

\medskip
\pause


\begin{alltt}
let d1 =
  Dir("d1",[File "a1";
            Dir("d2", [File "a2";
                       Dir("d3", [File "a3"])]);
            File "a4";
            Dir("d3", [File "a5"])
           ])
\end{alltt}

\medskip
\pause

\begin{center}
\redbrown The type of d1 is ?
\end{center}

\end{frame}

\begin{frame}[fragile]\frametitle{Mutually recursive function declarations}

\begin{itemize}
\item are combined using {\redbrown and}
\end{itemize}

\bigskip

Example: extract the names occurring in file systems and elements.

\begin{alltt}
let rec namesFileSys = function
  | []    -> []
  | e::es -> (namesElement e) @ (namesFileSys es)
{\redbrown{and}} namesElement = function
  | File s    -> [s]
  | Dir(s,fs) -> s :: (namesFileSys fs) ;;
\ett{val namesFileSys : Element list -> string list}
\ett{val namesElement : Element -> string list}
\end{alltt}

\medskip
\pause

\begin{alltt}
namesElement d1 ;;
\ett{val it : string list = ["d1"; "a1"; "d2"; "a2";}
\ett{                        "d3"; "a3"; "a4"; "d3"; "a5"]}
\end{alltt}


\end{frame}

\begin{frame}{Summary}

Finite Trees
\begin{itemize}
\item concepts
\item illustrative examples
\end{itemize}

\bigskip
\pause
Notice the strength of having trees as values.


\bigskip
\pause
Notice that polymorphic types and mutual recursion are NOT biased to trees.



\end{frame}

\end{document}
