% 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
{Interpreters for two simple languages\\
-- including exercises} % (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 25/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}{Purpose}

To show the power of a functional programming language, we present
a prototype for interpreters for a simple expression language with local declarations and a simple WHILE language.

\medskip


\begin{itemize} \item<2-> Concrete syntax: defined by a
contextfree grammar

\item<3-> Abstract syntax (parse trees): defined by algebraic
datatypes

\item<4-> Semantics, i.e.\ meaning of programs: inductively
defined following the structure of the abstract syntax
\end{itemize}
\pause[4] \hfill {\redbrown succinct programs, fast prototyping}

\bigskip
\pause[5]
The interpreter for the simple expression language is a higher-order function:
\[\blue eval : Program \to Environment \to Value \]

\medskip

The interpreter for a simple imperative programming
language is a higher-order function:
\[\blue I : Program \to State \to State \]
\end{frame}


\begin{frame}[fragile]\frametitle{Expressions with local declarations}

Concrete syntax:
\begin{alltt}\blue
a * (-3 + (let x = 5 in x + a))
\end{alltt}
\pause

The {\blue abstract syntax} is defined by an algebraic datatype:
\begin{alltt}\blue
type ExprTree = | Const of int
                | Ident of string
                | Minus of ExprTree
                | Sum   of ExprTree * ExprTree
                | Diff  of ExprTree * ExprTree
                | Prod  of ExprTree * ExprTree
                | Let of string * ExprTree * ExprTree;;
\end{alltt}

\pause
Example:
\begin{alltt}\blue
let et =
  Prod(Ident "a",
       Sum(Minus (Const 3),
           Let("x", Const 5, Sum(Ident "x", Ident "a"))));;
\end{alltt}

\end{frame}

\begin{frame}[fragile]\frametitle{Evaluation in Environments}

An {\em\redbrown environment} contains {\em\redbrown bindings} of
identifiers to values.

\medskip
\pause

A \texttt{let} tree
$\texttt{Let(} {\it str}\texttt{,} t_1 \texttt{,} t_2 \texttt{)}$
is evaluated as in an environment {\it env}:
\begin{enumerate}
\item Evaluate $t_1$ to value $v_1$
\item Evaluate $t_2$ in the {\it env} extended with the binding of {\it str}
to {\it v}.
\end{enumerate}

\medskip
\pause

An evaluation function
\begin{alltt}\blue
eval: ExprTree -> map<string,int> -> int
\end{alltt}
is defined as follows:
\begin{alltt}\blue
let rec eval t env =
    match t with
    | Const n      -> n
    | Ident s      -> Map.find s env
    | Minus t      -> - (eval t env)
    | Sum(t1,t2)   -> eval t1 env + eval t2 env
    | Diff(t1,t2)  -> eval t1 env - eval t2 env
    | Prod(t1,t2)  -> eval t1 env * eval t2 env
    | Let(s,t1,t2) -> let v1   = eval t1 env
                      let env1 = Map.add s v1 env
                      eval t2 env1;;
\end{alltt}



\end{frame}

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

Note that the meaning of a let expression is directly represented in the program.

\bigskip

Example
\begin{alltt}\blue
let env = Map.add "a" -7 Map.empty;;
eval et env;;
\ett{val it : int = 35}
\end{alltt}

\end{frame}


\begin{frame}[fragile]\frametitle{Example: Imperative Factorial program}

An example of concrete syntax for a factorial program:

{\blue
\begin{alltt}
{\redbrown \{Pre: x=K and x>=0\}}
   y:=1 ;
   while !(x=0)
   do (y:= y*x;x:=x-1)
{\redbrown \{Post: y=K!\}}
\end{alltt}
}

\bigskip
\pause

Typical ingredients
\begin{itemize}
\item<2-> Arithmetical expressions

\item<3-> Boolean expressions

\item<4-> Statements (assignments, sequential composition, loops,
$\ldots$
\end{itemize}

\end{frame}

\begin{frame}[fragile]\frametitle{Arithmetic Expressions}

\begin{itemize}

\item Grammar:
\[\blue  aExp\ ::-\ n\ |\ v\ |\ aExp + aExp\ | aExp \cdot aExp\ |\ aExp - aExp\ |\ ( aExp ) \]
where {\blue $n$} is an integer and {\blue $v$} is a variable.

\bigskip

\item<2-> The declaration for the abstract syntax follows the
grammar {\blue
\begin{verbatim}
type aExp =      (* Arithmetical expressions *)
   | N  of int             (* numbers        *)
   | V  of string          (* variables      *)
   | Add of aExp * aExp    (* addition       *)
   | Mul of aExp * aExp    (* multiplication *)
   | Sub of aExp * aExp;;  (* subtraction    *)
\end{verbatim}
}
\pause[3]

\medskip
The {\blue abstract syntax} is representation
independent (no '+', '-', '(',')', etc.), no ambiguities  --- one
works directly on syntax trees.


\end{itemize}
\end{frame}


\begin{frame}[fragile]\frametitle{Semantics of Arithmetic Expressions}
\begin{itemize}
\item A {\darkgreen state} maps variables to integers {\blue
\begin{verbatim}
   type state = Map<string,int>;;
\end{verbatim}
}

\medskip

\item<2-> The meaning of an expression is a function: {\blue
\begin{verbatim}
   A: aExp -> state -> int
\end{verbatim}
}

\medskip

\pause[3] defined inductively on the
  structure of arithmetic expressions
{\blue
\begin{verbatim}
let rec A a s      =
   match a with
    | N n         -> n
    | V x         -> Map.find x s
    | Add(a1, a2) -> A a1 s + A a2 s
    | Mul(a1, a2) -> A a1 s * A a2 s
    | Sub(a1, a2) -> A a1 s - A a2 s;;
\end{verbatim}
}
\end{itemize}
\end{frame}


\begin{frame}[fragile]\frametitle{Boolean Expressions}
\begin{itemize}
\item Abstract syntax {\blue
\begin{verbatim}
type bExp =     (* Boolean expressions      *)
   | TT                     (* true         *)
   | FF                     (* false        *)
   | Eq of ....             (* equality     *)
   | Lt of ....             (* less than    *)
   | Neg of ....            (* negation     *)
   | Con of ....       ;;   (* conjunction  *)
\end{verbatim}
}


\item<2-> Semantics {\blue B : bExp $\to$ State $\to$ bool} {\blue
\begin{verbatim}
let B b s =
   match b with
   | TT       -> true
   | ....
\end{verbatim}
}
\end{itemize}

\end{frame}


\begin{frame}[fragile]\frametitle{Statements: Abstract Syntax}

{\blue
\begin{verbatim}
type stm  =        (* statements                          *)
   | Ass of string * aExp       (* assignment             *)
   | Skip
   | Seq  of stm * stm          (* sequential composition *)
   | ITE   of bExp * stm * stm  (* if-then-else           *)
   | While of bExp * stm;;      (* while                  *)
\end{verbatim}}

\bigskip
\pause

Example of concrete syntax: {\blue \begin{verbatim}
   y:=1 ; while not(x=0) do (y:= y*x ; x:=x-1)
\end{verbatim}}

\bigskip

Abstract syntax {\redbrown ?}

\end{frame}



\begin{frame}{Update of states}

An imperative program performs a sequence of state updates.


\begin{itemize}
\item The expression
\[\redbrown \mathtt{update}\, y\, v\, s \] is the
state that is as {\redbrown $s$} except that {\redbrown $y$} is
mapped to {\redbrown $v$}.\pause[2] Mathematically: {\blue
\[ (\mathit{update}\, y\, v\, s)(x) = \left\{ \begin{array}{ll}
                                 v & \mbox{if $x=y$}\\
                                s(x)& \mbox{if $x \neq y$}
                               \end{array}
                       \right.
\]
}
\item<3->Update is a higher-order function with the
declaration:
{\blue
\begin{alltt}
let update x v s = Map.add x v s;;
\end{alltt}}

\item<3->{\darkgreen Type?}
\end{itemize}
\end{frame}


\begin{frame}[fragile]\frametitle{Interpreter for Statements}
\begin{itemize}
\item The meaning of statements is a function
\[\blue I: stm \to state \to state
\]
that is defined by induction on the structure of statements:
{\blue
\begin{verbatim}
let rec I stm s =
    match stm with
    | Ass(x,a)         -> update x ( ... ) s
    | Skip             -> ...
    | Seq(stm1, stm2)  -> ...
    | ITE(b,stm1,stm2) -> ...
    | While(b, stm)    -> ... ;;
\end{verbatim}}
\end{itemize}
\end{frame}


\begin{frame}[fragile]\frametitle{Example: Factorial function}
\begin{alltt}
(* \{pre: x = K and x>=0\}
      y:=1 ; while !(x=0) do (y:= y*x;x:=x-1)
   \{post: y = K!\}                                 *)
\pause

let fac = Seq(Ass("y", N 1),
              While(Neg(Eq(V "x", N 0)),
                    Seq(Ass("y", Mul(V "x", V "y")) ,
                        Ass("x", Sub(V "x", N 1)) )));;

\pause
(* Define an initial state                           *)
let s0 = Map.ofList [("x",4)];;
\ett{val s0 : Map<string,int> = map [("x", 4)]}

\pause
(* Interpret the program                             *)
let s1 = I fac s0;;
\ett{val s1 : Map<string,int> = map [("x", 1); ("y", 24)]}
\end{alltt}

\end{frame}

\begin{frame}{Exercises}
\begin{itemize}

\item Complete the program skeleton for the interpreter, and try
some examples.

\bigskip

\item Extend the abstract syntax and the interpreter with {\blue if-then} and {\blue repeat-until}
statements.

\bigskip

\item Suppose that an expression of the form {\blue $inc(x)$} is
added. It adds one to the value of {\blue $x$} in the current
state, and the value of the expression is this new value of {\blue
$x$}.
\medskip

How would you refine the interpreter to cope with this construct?

\end{itemize}

\end{frame}
\end{document}
