% 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
{Sequences} % (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 15/11/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}{Sequences (or Lazy Lists)}

\begin{itemize}
\item {\em\redbrown lazy evaluation} or {\em\redbrown delayed
evaluation} is the technique of delaying a computation until the
result of the computation is needed.
\end{itemize}
\ \hfill Default in lazy languages like Haskell
\bigskip

\pause
\begin{center}\redbrown It is occasionally efficient to be lazy.
\end{center}

\bigskip
\pause

A special form of this is {\em\redbrown Sequences}, where the
elements are not evaluated until their values are required by the
rest of the program.

\begin{itemize}
\item a {\em\redbrown sequence} may be infinite\\
\ \hfill \hfill just a finite part of a it is
used in computations
\end{itemize}

\bigskip

\pause
Example:
\begin{itemize}

\item Consider the sequence of all prime numbers: $\blue 2,3, 5,7,
11, 13, 17, 19, 23, \ldots$

\item the first $\redbrown 5$ are $\blue 2,3,5,7,11$\\
\ \hfill {\darkgreen Sieve of Eratosthenes}

\end{itemize}


\end{frame}

\begin{frame}[fragile]
\frametitle{Delayed computations}

The computation of the value of $\blue e$ can be delayed by "packing" it into a function (a {\redbrown closure}):
\[\blue \verb!fun () ->!\ e \]

\pause

Example:
\begin{alltt}
fun () -> 3+4;;
\ett{val it : unit -> int = <fun:clo@10-2>}

it();;
\ett{val it : int = 7}
\end{alltt}

The addition is deferred until the closure is applied.

\end{frame}


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

One can make it visible when computations are performed by use of side effects:
\begin{alltt}\blue
let idWithPrint i = let _ = printfn "\%d" i
                    i;;
\ett{val idWithPrint : int -> int}

idWithPrint 3;;
\ett{3}
\ett{val it : int = 3}
\end{alltt}
The value is printed before it is returned.

\medskip
\pause

\begin{alltt}\blue
fun () -> (idWithPrint 3) + (idWithPrint 4);;
\ett{val it : unit -> int = <fun:clo@14-3>}
\end{alltt}
Nothing is printed yet.

\medskip
\pause

\begin{alltt}\redbrown
it();;
\ett{3}
\ett{4}
\ett{val it : int = 7}
\end{alltt}


\end{frame}


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

A lazy list or {\em\redbrown sequence} in F\# is a possibly infinite, ordered collection of elements, where the elements are computed {\redbrown by demand} only.

\bigskip
\pause

A natural number sequence $\blue 0, 1, 2, \ldots$ is created as follows:
\begin{alltt}\blue
let nat ={\redbrown Seq.initInfinite} (fun i -> i);;
\ett{val nat : seq<int>}
\end{alltt}

\pause
\bigskip

A \verb!nat! element is computed by demand only:
\begin{alltt}\blue
let nat = Seq.initInfinite idWithPrint;;
\ett{val nat : seq<int>}

Seq.nth 4 nat;;
4
val it : int = 4
\end{alltt}

%\pause
%\medskip

%\begin{itemize}
%\item Lists and Array are specializations of Sequences (in an OO-sense). Hence these libraries have many similarities.
%\end{itemize}

\end{frame}

\begin{frame}[fragile]
\frametitle{Further examples}

A sequence of even natural numbers is easily obtained:
\begin{alltt}\blue
let even = Seq.filter (fun n -> n\%2=0) nat;;
\ett{val even : seq<int>}

Seq.toList(Seq.take 4 even);; \pause
\ett{0}
\ett{1}
\ett{2}
\ett{3}
\ett{4}
\ett{5}
\ett{6}
\ett{val it : int list ={\redbrown [0; 2; 4; 6]}}
\end{alltt}

\pause
\medskip

Demanding the first 4 even numbers demands a computation of the first 7 natural numbers.

\end{frame}



\begin{frame}{Sieve of Eratosthenes}

Greek mathematician (194 -- 176 BC)

\medskip

Computation of prime numbers

\begin{itemize}
\item start with the sequence $\blue 2, 3, 4, 5, 6, ...$\\
select head ($\blue 2$), and remove multiples of $2$ from the
sequence\\
\ \hfill $\redbrown 2$


\item<2-> next sequence $\blue 3, 5, 7, 9, 11, ...$\\
select head ($\blue 3$), and remove multiples of $3$ from the sequence\\
\ \hfill $\redbrown 2, 3$

\item<3-> next sequence $\blue 5, 7, 11, 13, 17, ...$\\
select head ($\blue 5$), and remove multiples of $5$ from the sequence\\
\ \hfill $\redbrown 2, 3, 5$

\item<3-> $\redbrown \vdots$
\end{itemize}

\end{frame}


\begin{frame}[fragile]
\frametitle{Sieve of Eratosthenes in F\# (I)}

Remove multiples of $\blue a$ from sequence $\blue sq$: {\blue
\begin{alltt}
let sift a sq = Seq.filter (fun n -> n % a <> 0) sq;;
\ett{val sift : int -> seq<int> -> seq<int>}
\end{alltt}
}

\pause
\medskip

Select head and remove multiples of head from the tail -- {\redbrown recursively}:

{\blue
\begin{alltt}
let rec sieve sq =
   Seq.delay (fun () ->
                  let p = Seq.nth 0 sq
                  Seq.append
                    (Seq.singleton p)
                    (sieve(sift p (Seq.skip 1 sq))));;
\ett{val sieve : seq<int> -> seq<int>}
\end{alltt}
}

\begin{itemize}

\item Delay is needed to avoid infinite recursion

\item {\blue Seq.append} is the sequence sibling to {\blue \verb!@!}

\item {\blue Seq.nth 0 sq} gives the head of {\blue sq}

\item {\blue Seq.skip 1 sq} gives the tail of {\blue sq}

\end{itemize}


\end{frame}

\begin{frame}[fragile]
\frametitle{Examples}
The sequence of prime numbers and the $\blue n$'th prime number:
{\blue
\begin{alltt}
let primes = sieve(Seq.initInfinite (fun n -> n+2));;
\ett{val primes : seq<int>}

let nthPrime n = Seq.nth n primes;;
\ett{val nthPrime : int -> int}

nthPrime 100;;
\ett{val it : int = 547}
\end{alltt}
}

\pause
\medskip

Re-computation can be avoided by using cached sequences:
{\blue
\begin{alltt}
let primesCached ={\redbrown} Seq.cache primes;;

let nthPrime' n = Seq.nth n primesCached;;
\ett{val nthPrime' : int -> int}
\end{alltt}}
Computing the 700'th prime number takes about 8s;
a subsequent computation of the 705'th is fast since that computation starts from the 700 prime number
\end{frame}


\begin{frame}[fragile]
\frametitle{Sieve of Eratosthenes using Sequence Expressions}

{\redbrown Sequence expressions} can be used for defining step-by-step generation of sequences.

\pause
\medskip

The sieve of Erastothenes:

{\blue
\begin{alltt}
let rec sieve sq =
  {\redbrown seq \{} let p = Seq.nth 0 sq
        {\redbrown yield} p
        {\redbrown yield!} sieve(sift p (Seq.skip 1 sq)){\redbrown \}};;
\ett{val sieve : seq<int> -> seq<int>}
\end{alltt}
}

\pause

\newcommand{\seqexp}{\mathit{seqexp}}
\begin{itemize}

\item<3-> By construction lazy -- no explicit \verb!Seq.delay! is needed

\item<4-> $\redbrown \verb!yield!\ x$  adds the element $\blue x$ to the generated sequence

\item<5-> $\redbrown \verb:yield!:\ \mathit{sq}$ adds the sequence $\blue \mathit{sq}$ to the generated sequence

\item<6-> \mbox{$\redbrown \begin{array}{l}
\seqexp_1\\
\seqexp_2
\end{array}
$}
appends the sequence of $\blue \seqexp_1$ to that of
$\blue \seqexp_2$
\end{itemize}
\end{frame}

\begin{frame}[fragile]
\frametitle{Example: Catalogue search (I)}

Extract (recursively) the sequence of all files in a directory:
\begin{alltt}\blue\small
open System.IO ;;

let rec allFiles dir =
  seq \{yield! Directory.GetFiles dir
       yield! Seq.collect allFiles (Directory.GetDirectories dir)\};;
\ett{val allFiles : string -> seq<string>}
\end{alltt}
where $\blue \verb!Seq.collect: ('a -> seq<'c>) -> seq<'a> -> seq<'c>!$ combines a 'map' and 'concatenate' functionality.

\pause
\bigskip

\begin{alltt}\blue\small
Directory.SetCurrentDirectory @"C:{\ttbsl}mrh{\ttbsl}Forskning{\ttbsl}Cambridge{\ttbsl}";;
let files = allFiles ".";;
\ett{val files : seq<string>}

Seq.nth 100 files;;
\ett{val it : string = ".{\ttbsl}BOOK{\ttbsl}Satisfiability.fs"}
\end{alltt}
Nothing is computed beyond element 100.

\end{frame}

\begin{frame}[fragile]
\frametitle{Example: Catalogue search (II)}

We want to search for files with certain extensions, e.g.\ as follows:

\begin{alltt}\blue\small
let funFiles=Seq.cache ({\redbrown{searchFiles}} (allFiles ".") ["fs";"fsi"]);;
\ett{val funFiles : seq<string * string * string>}

Seq.nth 0 funFiles;;
\ett{val it: string * string * string= (".{\ttbsl}", "CatalogueSearch", "fs")}

Seq.nth 6 funFiles;;
\ett{val it : string * string * string = (".{\ttbsl}BOOK{\ttbsl}", "Curve", "fsi")}

Seq.nth 11 funFiles;;
\ett{val it : string * string * string }
\ett{       = (".{\ttbsl}BOOK{\ttbsl}", "Satisfiability", "fs")}
\end{alltt}

\bigskip
\pause

\begin{itemize}

\item a sequence in chosen so that the search is terminated when the wanted file is found
\item a cached sequence in chosen to avoid re-computation
\end{itemize}

\end{frame}

\begin{frame}[fragile]
\frametitle{Example: Catalogue search (III)}

The search function ca be declared using regular expressions:

\begin{alltt}\small
open System.Text.RegularExpressions ;;

let rec searchFiles files exts =
    let{\blue reExts} = List.foldBack (fun ext re -> ext+"|"+re) exts ""
    let re = Regex (@"{\ttbsl}G({\redbrown{{\ttbsl}S*{\ttbsl}{\ttbsl}}})({\darkgreen{[^{\ttbsl}{\ttbsl}]+}}){\ttbsl}.(" +{\blue reExts} + ")$")
    seq \{for fn in files do
            let m = re.Match fn
            if m.Success
            then let path = captureSingle m 1
                 let name = captureSingle m 2
                 let ext  = captureSingle m 3
                 yield (path, name, ext)      \};;
\ett{val searchFiles : seq<string> -> string list}
\ett{                  -> seq<string * string * string>}
\end{alltt}

\bigskip
\pause

\begin{itemize}

\item {\blue \verb!reExts!} is a regular expression matching the extensions

\item The path matches the regular expression {\redbrown \verb!\S*\\!}

\item The file name matches the regular expression {\darkgreen \verb![^\\]+!}

\item The function \verb!captureSingle! can extract captured strings
\end{itemize}

\end{frame}

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

\begin{itemize}

\item Anonymous functions \texttt{\blue fun () -> $e$}
can be used to {\blue delay the computation} of $\blue e$.

\item<2-> Possibly infinite sequences provide natural and useful abstractions

\item<3-> The computation by demand only is convenient in many applications

\end{itemize}

\pause[4]

\begin{center}\redbrown It is occasionally efficient to be lazy.
\end{center}

\bigskip
\pause[5]
The type  {\blue \verb!seq<'a>!} is a synonym for the .NET type {\blue \verb!IEnumerable<'a>!}.

\medskip

Any .NET type that implements this interface can be used as a sequence.
\begin{itemize}
\item Lists, arrays and databases, for example.
\end{itemize}

\end{frame}
\end{document}
