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

\usepackage{epsf,epsfig}

\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 11:\\ Imperative, Asynchronous, Parallel and Monadic Programming\\
\qquad A short story} % (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 29/11/2012}% (optional)


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

\begin{itemize}

\item Imperative programming,

\item asynchronous programming,

\item parallel programming, and

\item monadic programming

\end{itemize}
by simple examples.

\end{frame}


\begin{frame}[fragile]
\frametitle{What is this?}

\begin{verbatim}
let  ...
   let rec visit u =
      color.[u] <- Gray ; time := !time + 1; d.[u] <- !time
      let rec h v = if color.[v] = White
                    then  pi.[v]  <- u
                          visit v
      List.iter h (adj.[u])
      color.[u] <- Black
      time      := !time + 1
      f.[u]     <- !time

   let mutable i = 0
   while i < V do
      if color.[i] = White
      then visit i
      i <- i + 1
   (d, f, pi);;

\end{verbatim}

\end{frame}

\begin{frame}[fragile]
\frametitle{Depth-First Search of directed graphs}

"Direct" translation of pseudocode from Corman, Leiserson, Rivest.

\medskip

Remaining parts:
\begin{alltt}\blue
type color = White | Gray | Black;;

let dfs(V,adj: int list[]) =
   let color        = Array.create V White
   let pi           = Array.create V -1
   let d            = Array.create V -1
   let f            = Array.create V -1
   let time         = ref 0
   let rec visit u =
          ....

   let mutable i = 0
   while i < V do
      ....
   (d, f, pi);;
\end{alltt}

\end{frame}

\begin{frame}[fragile]
\frametitle{DFS -- an example}

{\blue
\begin{alltt}

val (d,f,pi) = dfs(g6);

\end{alltt}
}
\bigskip


\begin{tabular}{ll}
\begin{minipage}{5.5cm}
\pause[1] {{\blue
\[\begin{array}{lcl}
d & : &  \mbox{Discovery times}\\
f & : &  \mbox{Finishing times}\\
pi & : & \mbox{Predecessors}
\end{array}
\]

\bigskip

\bigskip


A node $\blue i$ is marked $\redbrown d_i/f_i$


}}
\end{minipage}
&
\begin{minipage}{5.5cm}
\begin{center}
\epsfig{file=G6res.eps, width=5cm, angle=0}
%\caption{ARTS: A System-Level Framework for a MPSoC} \label{fi:MPSoC}
\end{center}
\end{minipage}
\end{tabular}
\end{frame}



\begin{frame}{Elements of imperative F\#}

A {\em\darkgreen store} is a table associating values $v_i$ with
locations $l_i$:
\[\darkgreen
\left[
\begin{array}{lcl}
l_1 & \mapsto & v_1 \\
l_2 & \mapsto & v_2 \\
\multicolumn{3}{c}{\ldots} \\
l_n & \mapsto & v_n \\
\end{array}
\right]
\]

\end{frame}

\begin{frame}[fragile]
\frametitle{Allocation of a new cell in the store}

\begin{alltt}
let mutable x = 1;;
\ett{val mutable x : int = 1}

let mutable y = 3;;
\ett{val mutable y : int = 3}
\end{alltt}

\pause
\bigskip

Results in the following environment and store:
\[
\begin{array}{lcl}
\mbox{Environment} &\ \ \ \ & \mbox{Store \vspace{0.5mm}} \\
{\darkgreen \left[
\begin{array}{lcl}
\verb/x/ & \mapsto & l_1 \\
\verb/y/ & \mapsto & l_2 \\
\end{array}
\right]} && {\darkgreen \left[
\begin{array}{lcl}
l_1 & \mapsto & 1 \\
l_2 & \mapsto  & 3 \\
\end{array}
\right]}
\end{array}
\]

\pause
\bigskip

A similar effect is achieved by:
\begin{alltt}
let x = ref 1;;
let y = ref 3;;
\end{alltt}

\end{frame}

\begin{frame}[fragile]
\frametitle{Value in a location in the store and Assignment}

Given the following environment and store:
\[
\begin{array}{lcl}
\mbox{Environment} &\ \ \ \ & \mbox{Store \vspace{0.5mm}} \\
{\darkgreen \left[
\begin{array}{lcl}
\verb/x/ & \mapsto & l_1 \\
\verb/y/ & \mapsto & l_2 \\
\end{array}
\right]} && {\darkgreen \left[
\begin{array}{lcl}
l_1 & \mapsto & 1 \\
l_2 & \mapsto  & 3 \\
\end{array}
\right]}
\end{array}
\]


\bigskip
\pause

The assignment \texttt{\blue x\ <-\ y+2} results in the new store:
\[ \darkgreen
\left[
\begin{array}{lcl}
l_1 & \mapsto & 5 \\
l_2 & \mapsto  & 3 \\
\end{array}
\right]
\]

\bigskip
\pause

A similar effect is achieved by the assignment \texttt{\blue x\ :=\ !y + 2}
\begin{itemize}
\item The assignment \verb!x := ...! is used
\item The explicit ``contentsOf'' \verb?!y? is necessary
\end{itemize}
when \verb?let x = ref ...? and \verb?let y = ref ...? are used


\end{frame}

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

\begin{itemize}
\item \mbox{} "'a [] is the type of one-dimensional,
mutable, zero-based constant-time-access arrays with elements of type 'a."

\end{itemize}

\bigskip
\pause
{\blue $\verb!Array.create!\ n\ v$} creates an array with $\blue n$ entries all containing  $\blue v$


\bigskip

Examples:

{\blue
\begin{alltt}
let a = Array.create 5 "a";;
\ett{val a :{\redbrown string []} = [|"a"; "a"; "a"; "a"; "a"|]}

a.[2] <- "b";;
\ett{val it :{\redbrown unit} = ()}

a;;
\ett{val it : string [] = [|"a"; "a";{\redbrown "b"}; "a"; "a"|]}

a.[0];;
\ett{val it : string = "a"}
\end{alltt}
}
\end{frame}

\begin{frame}[fragile]
\frametitle{Graph representation: neighbour-list}

\begin{tabular}{ll}
\begin{minipage}{5.5cm}
\pause[2] {\blue
\begin{alltt}
let adj =
   Array.ofList [ [1;3];
                  [4];
                  [4;5];
                  [1];
                  [3];
                  [5]]  ;;

let g6 = (6,adj);;
\pause

g6;;
\ett{val it : int * int list []}
\ett{    = (6, [|[1; 3]; [4]; [4; 5]; [1]; [3]; [5]|])}
\end{alltt}
}
\end{minipage}
&
\begin{minipage}{6cm}
\begin{center}
\epsfig{file=G6.eps, width=5cm, angle=0}
%\caption{ARTS: A System-Level Framework for a MPSoC} \label{fi:MPSoC}
\end{center}
\end{minipage}
\end{tabular}

\end{frame}


\begin{frame}[fragile]
\frametitle{Inspecting results}

{\blue
\begin{alltt}

val (d,f,pi) = dfs(g6);

\end{alltt}
}
\bigskip


\begin{tabular}{ll}
\begin{minipage}{5.5cm}
\pause[2] {{\blue
\begin{alltt}
d;;  (* Discovery times *)
\ett{val it : int []}
\ett{  = [|1; 2; 9; 4; 3; 10|]}

\pause[3]
f;;  (* Finishing times *)
\ett{val it : int []}
\ett{  = [|8; 7; 12; 5; 6; 11|]}
\pause[4]

pi;; (* Predecessors    *)
\ett{val it : int []}
\ett{   = [|-1; 0; -1; 4; 1; 2|]}
\end{alltt}}}
\end{minipage}
&
\begin{minipage}{5.5cm}
\begin{center}
\epsfig{file=G6res.eps, width=5cm, angle=0}
%\caption{ARTS: A System-Level Framework for a MPSoC} \label{fi:MPSoC}
\end{center}
\end{minipage}
\end{tabular}
\end{frame}

\begin{frame}

\begin{itemize}

\item F\# is an excellent imperative language

\bigskip

\bigskip

\item the combination of imperative and applicative constructs is
powerful
\end{itemize}
\end{frame}

\begin{frame}[fragile]{Asynchronous computations by example}

\begin{alltt}\blue
open System;;
open System.Net;;
let downLoadDTUcomp =
  async {\ttlbrace}
    let webCl = new WebClient()
    let! html = webCl.AsyncDownloadString(
                     Uri "http://www.dtu.dk")
    return html{\ttrbrace} ;;
\ett{ val downLoadDTUcomp : Async<string>}
\end{alltt}
\begin{enumerate}
\item<2-> Create a \texttt{WebClient} object.
\item<3-> Initiate the download using \texttt{AsyncDownloadString}. This function makes the
task an wait item and will eventually terminate when the download has completed.\\
It uses no thread while waiting.
\item<4-> At termination the rest of the computation is  re-started
with the identifier \texttt{html} bound to the result.
\item<5-> The expression \texttt{return}\;\texttt{html} returns the value bound to \texttt{html},
that is, the result of the download.
\end{enumerate}
\end{frame}

\begin{frame}[fragile]{Parallel downloads of web pages}
\begin{alltt}\blue
let downloadComp url =
    let webCl = new WebClient()
    async {\ttlbrace}let! html = webCl.AsyncDownloadString(Uri url)
           return html{\ttrbrace};;
\end{alltt}

\medskip
\pause
A computation for parallel downloads:
\begin{alltt}\blue
let downlArrayComp (urlArr: string[]) =
    Async.Parallel (Array.map downloadComp urlArr);;
\ett{val downlArrayComp : string [] ->{\redbrown Async<string []>}}
\end{alltt}

\medskip
\pause
{\redbrown Activation} of the computation:
\begin{alltt}
let paralDTUandMScomp =
  downlArrayComp
    [|"http://www.dtu.dk"; "http://www.microsoft.com"|];;

Array.map (fun (s:string) -> s.Length)
          (Async.RunSynchronously paralDTUandMScomp);;
\ett{val it : int [] = [|45199; 1020|]}
\ett{Real: 00:00:02.235, \redbrown CPU: 00:00:00.046}
\end{alltt}
Uses limited CPU time.
\end{frame}

\begin{frame}[fragile]{Parallel computation -- exploiting multiple cores}

\begin{alltt}\blue
type BinTree<'a> = | Leaf
                   | Node of BinTree<'a>*'a*BinTree<'a>;;
let rec exists p t =
    match t with
    | Leaf                 -> false
    | Node(_,v,_) when p v -> true
    | Node(tl,_,tr)        -> exists p tl || exists p tr;;
\end{alltt}

\pause
Sequential search in big trees:
\begin{alltt}\blue
let rec genTree n range =
    if n=0 then Leaf
    else let tl = genTree (n-1) range
         let tr = genTree (n-1) range
         Node(tl,{\redbrown gen range}, tr);;
let t = genTree 25 10000;;

exists (fun n ->{\redbrown isPrime n} && n>10000) t;;
\ett{Real: 00:01:22.818, CPU: 00:01:22.727}
\ett{val it : bool = false}
\end{alltt}
\end{frame}

\begin{frame}[fragile]{Parallel search in big trees}

\begin{alltt}\blue
open{\redbrown System.Threading.Tasks};;
let rec parExistsDepth p t n =
  if n=0 then exists p t else
  match t with
  | Leaf                 -> false
  | Node(_,v,_) when p v -> true
  | Node(tl,_,tr)        ->
      let b1 ={\redbrown Task.Factory.StartNew}(
                   fun () -> parExistsDepth p tl (n-1))
      let b2 ={\redbrown Task.Factory.StartNew}(
                   fun () -> parExistsDepth p tr (n-1))
      b1.Result||b2.Result;;
\ett{val parExistsDepth: ('a->bool)->BinTree<'a>->int->bool}
\end{alltt}

\bigskip
\pause

Experiments show that the best result is obtained using depth 4:
\begin{alltt}\blue
parExistsDepth (fun n -> isPrime n && n>10000) t 4;;
\ett{Real:{\redbrown 00:00:35.303}, CPU: 00:02:18.669}
\end{alltt}
The speedup is approximately 2.3.

\end{frame}

\begin{frame}[fragile]{Defining computation expressions}
also called workflows or monads.

\medskip

Purpose: hide low-level details in a builder class.

\medskip
\pause

Expression evaluation with error handling:
\begin{alltt}\blue
let I e env =
  let rec eval = function
      | Num i      -> Some i
      | Var x      -> Map.tryFind x env
      | Add(e1,e2) -> match (eval e1, eval e2) with
                      | (Some v1, Some v2) -> Some(v1+v2)
                      | _                  -> None
      | Div(e1,e2) -> match (eval e1, eval e2) with
                      | (_ , Some 0)       -> None
                      | (Some v1, Some v2) -> Some(v1/v2)
                      | _                  -> None
  eval e;;
\end{alltt}

\medskip
\pause
How can the Some/None manipulations be hidden?
\end{frame}

\begin{frame}[fragile]{Declaring a computation builder object}
Define the computation type:
\begin{alltt}\blue
type maybe<'a> = option<'a>;;
\end{alltt}

\medskip
\pause

Define a computation builder class:
\begin{alltt}\blue
type MaybeClass() =
    member bld.Bind(m:maybe<'a>,f:'a->maybe<'b>):maybe<'b> =
        match m with | None   -> None
                     | Some a -> f a
    member bld.Return a:maybe<'a> = Some a
    member bld.ReturnFrom m:maybe<'a> = m
    member bld.Zero():maybe<'a> = None;;
\end{alltt}

\medskip
\pause
Declare a computation builder object:
\begin{alltt}\blue
let maybe = MaybeClass();;
\end{alltt}
\medskip
\pause
\begin{center}
Many improvements are possible, e.g. to delay computations
\end{center}

\end{frame}

\begin{frame}[fragile]{Using the builder object}

\begin{center}\darkgreen
The Some/None manipulations are now hidden
\end{center}

\medskip

\begin{alltt}\blue
let I e env =
    let rec eval = function
        | Num i      ->{\redbrown maybe} {\ttlbrace}return i{\ttrbrace}
        | Var x      ->{\redbrown maybe} {\ttlbrace}return! Map.tryFind x env{\ttrbrace}
        | Add(e1,e2) ->{\redbrown maybe} {\ttlbrace}let! v1 = eval e1
                               let! v2 = eval e2
                               return v1+v2{\ttrbrace}
        | Div(e1,e2) ->{\redbrown maybe} {\ttlbrace}let! v2 = eval e2
                               if v2<>0 then
                                  let! v1 = eval e1
                                  return v1/v2{\ttrbrace}
    eval e;;
\ett{val I : expr -> Map<string,int> -> maybe<int>}
\end{alltt}

\end{frame}

\begin{frame}

\begin{center}\redbrown

F\# supports a rich collection of different programming paradigms


\end{center}


\end{frame}

\end{document}
