FUNCTIONAL PROGRAMMING IN ERLANG ID1218 Lecture 022009-10-28 Christian Schulte Software and Computer Systems School of Information and.

Slides:



Advertisements
Similar presentations
1 Programming Languages (CS 550) Mini Language Interpreter Jeremy R. Johnson.
Advertisements

CSE341: Programming Languages Lecture 2 Functions, Pairs, Lists Dan Grossman Winter 2013.
CMSC 330: Organization of Programming Languages Tuples, Types, Conditionals and Recursion or “How many different OCaml topics can we cover in a single.
C. Varela; Adapted w/permission from S. Haridi and P. Van Roy1 Declarative Programming Techniques Accumulators, Difference Lists (VRH ) Carlos Varela.
C O N T E X T - F R E E LANGUAGES ( use a grammar to describe a language) 1.
Getting started with ML ML is a functional programming language. ML is statically typed: The types of literals, values, expressions and functions in a.
Lambda Calculus and Lisp PZ03J. Lambda Calculus The lambda calculus is a model for functional programming like Turing machines are models for imperative.
ML: a quasi-functional language with strong typing Conventional syntax: - val x = 5; (*user input *) val x = 5: int (*system response*) - fun len lis =
Introduction to Computability Theory
MINI ERLANG ID1218 Lecture Christian Schulte Software and Computer Systems School of Information and Communication Technology.
0 PROGRAMMING IN HASKELL Chapter 7 - Higher-Order Functions.
0 PROGRAMMING IN HASKELL Chapter 6 - Recursive Functions Most of this should be review for you.
1 Executing Method Calls This lecture tells you precisely how method calls are executed (a few details will have to wait until we get to classes and objects).
0 PROGRAMMING IN HASKELL Chapter 6 - Recursive Functions.
SUMMARY ID1218 Lecture Christian Schulte Software and Computer Systems School of Information and Communication Technology.
ITERATIVE COMPUTATIONS CONCURRENCY ID1218 Lecture Christian Schulte Software and Computer Systems School of Information and.
UNIVERSITY OF SOUTH CAROLINA Department of Computer Science and Engineering Introduction to Functional Programming Notes for CSCE 190 Based on Sebesta,
CS 2104 : Prog. Lang. Concepts. Functional Programming I Lecturer : Dr. Abhik Roychoudhury School of Computing From Dr. Khoo Siau Cheng’s lecture notes.
2.2 A Simple Syntax-Directed Translator Syntax-Directed Translation 2.4 Parsing 2.5 A Translator for Simple Expressions 2.6 Lexical Analysis.
Towers of Hanoi. Introduction This problem is discussed in many maths texts, And in computer science an AI as an illustration of recursion and problem.
17-Sep-15 Erlang. Running Erlang Double-click on the Erlang icon, or type erl into a terminal (cmd) window You can try short pieces of code from here,
0 REVIEW OF HASKELL A lightening tour in 45 minutes.
0 PROGRAMMING IN HASKELL Chapter 7 - Defining Functions, List Comprehensions.
Computer Science Department Data Structure & Algorithms Lecture 8 Recursion.
Review Introduction to Searching External and Internal Searching Types of Searching Linear or sequential search Binary Search Algorithms for Linear Search.
CS 326 Programming Languages, Concepts and Implementation Instructor: Mircea Nicolescu Lecture 8.
Chapter 9: Functional Programming in a Typed Language.
Functional Programming With examples in F#. Pure Functional Programming Functional programming involves evaluating expressions rather than executing commands.
Overview of the Haskell 98 Programming Language
1 The Evaluator. 2 Compiler vs. Interpreter Command Processing Unit The Computer Program in Low Level Machine Language Program in High Level Language.
C. Varela; Adapted w. permission from S. Haridi and P. Van Roy1 Functional Programming: Lists, Pattern Matching, Recursive Programming (CTM Sections ,
CSE 341 : Programming Languages Lecture 2 Functions, Pairs, Lists Zach Tatlock Spring 2014.
Basic Scheme February 8, 2007 Compound expressions Rules of evaluation Creating procedures by capturing common patterns.
1Computer Sciences Department. Book: INTRODUCTION TO THE THEORY OF COMPUTATION, SECOND EDITION, by: MICHAEL SIPSER Reference 3Computer Sciences Department.
1 Lecture 14: Assignment and the Environment Model (EM)
1 Programming Languages (CS 550) Lecture 2 Summary Mini Language Interpreter Jeremy R. Johnson.
CMSC 330: Organization of Programming Languages Operational Semantics.
Functional Programming Lecture 3 - Lists Muffy Calder.
1 Proving Properties of Recursive List Functions CS 270 Math Foundations of CS Jeremy Johnson.
Functions.
Functional Programming: Lists, Pattern Matching, Recursive Programming (CTM Sections , 3.2, , 4.7.2) Carlos Varela RPI September 12,
ML: a quasi-functional language with strong typing
A Simple Syntax-Directed Translator
CSE341: Programming Languages Lecture 6 Nested Patterns Exceptions Tail Recursion Dan Grossman Spring 2017.
A lightening tour in 45 minutes
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
Mini Language Interpreter Programming Languages (CS 550)
Algorithm design and Analysis
The Metacircular Evaluator
An aggregation mechanism
Functional Programming
CSE341: Programming Languages Lecture 6 Nested Patterns Exceptions Tail Recursion Dan Grossman Spring 2013.
CSE341: Programming Languages Lecture 6 Nested Patterns Exceptions Tail Recursion Dan Grossman Autumn 2018.
CSCE 314: Programming Languages Dr. Dylan Shell
PROGRAMMING IN HASKELL
CSE341: Programming Languages Lecture 6 Nested Patterns Exceptions Tail Recursion Zach Tatlock Winter 2018.
CSE 3302 Programming Languages
Declarative Computation Model Single assignment store (VRH 2
Announcements Quiz 5 HW6 due October 23
CSCE 314: Programming Languages Dr. Dylan Shell
CSE341: Programming Languages Lecture 6 Nested Patterns Exceptions Tail Recursion Dan Grossman Spring 2016.
PROGRAMMING IN HASKELL
Introduction to the Lab
CSE341: Programming Languages Lecture 6 Nested Patterns Exceptions Tail Recursion Dan Grossman Spring 2019.
Brett Wortzman Summer 2019 Slides originally created by Dan Grossman
CSE341: Programming Languages Lecture 6 Nested Patterns Exceptions Tail Recursion Dan Grossman Autumn 2017.
Presentation transcript:

FUNCTIONAL PROGRAMMING IN ERLANG ID1218 Lecture Christian Schulte Software and Computer Systems School of Information and Communication Technology KTH – Royal Institute of Technology Stockholm, Sweden

Reminder & Overview L02, ID1218, Christian Schulte

Functional Programming L02, ID1218, Christian Schulte 3  Compute by evaluating functions returning results  Techniques recursion with last-call-optimization pattern matching list processing higher-order programming accumulators

Functional Programming in Erlang L02, ID1218, Christian Schulte 4  Data types: values primitive: integers, floats, atoms compound: tuples, lists  Programs consist of functions identified by atom and arity defined by several clauses arguments are passed by value clauses are evaluated evaluation returns value

Function Definition L02, ID1218, Christian Schulte 5  Function defined by several clauses clauses separated by ; last clause terminated by. variable scope is per clause (anonymous variable _)  Clause consists of head and body separated by -> head can contain guard after when clauses tried in textual order until matching clause is found (pattern matches and guard is true)  Guards: tests, comparisons, conjunction, disjunction

Program Organization  Programs consists of several modules  Module are named export functions import other modules  Function calls either locally defined or imported functions or functions qualified by module name L02, ID1218, Christian Schulte 6

Overview L02, ID1218, Christian Schulte 7  Introduction to Erlang second look: lists and tuples, pattern matching third look: what do we need to understand  How do Erlang programs compute make programs simple how exactly does computation proceed  Next lecture accumulators higher-order programming

A Second Look L02, ID1218, Christian Schulte

Tuples L02, ID1218, Christian Schulte 9  Combine several values here: 1, a, 2 position is significant! {1,a,2} {} 1a2

Lists L02, ID1218, Christian Schulte 10  A list contains a sequence of elements  A list is the empty list [], or consists of a cons (or list pair) with head and tail head contains an element tail contains a list

An Example List L02, ID1218, Christian Schulte 11  After evaluation of [a|[b|[c|[]]]]  Can also be written as [a,b,c] [a|[b,c]] [a,b|[c|[]]] [|] a| b| c[]

Head And Tail L02, ID1218, Christian Schulte 12  The head and tail can be accessed by builtin functions (BIFs) hd/1 and tl/1 hd([X|Xr]) evaluates to X tl([X|Xr]) evaluates to Xr

Example of Head and Tail L02, ID1218, Christian Schulte 13  hd([a,b,c]) evaluates to a  tl([a,b,c]) evaluates to [b,c]  hd(tl(tl([a,b,c]))) evaluates to c  Draw the trees!

How to Process Lists L02, ID1218, Christian Schulte 14  Given: list of integers  Wanted: sum of its elements implement function sum  Inductive definition over list structure Sum of empty list is 0 Sum of non-empty list Xs is hd(Xs) + sum(tl(Xs))

Sum of a List L02, ID1218, Christian Schulte 15 sum(Xs) when Xs==[] -> 0; sum(Xs) -> hd(Xs)+sum(tl(Xs)).

General Method L02, ID1218, Christian Schulte 16  Lists are processed recursively base case:list is empty ([]) inductive case:list is cons access head, access tail  Powerful and convenient technique pattern matching matches patterns of values and provides access to fields of compound data structures

Sum with Pattern Matching L02, ID1218, Christian Schulte 17 sum([]) -> 0; sum([X|Xr]) -> X+sum(Xr).

Pattern Matching L02, ID1218, Christian Schulte 18  A pattern is constructed like a value but also allows variables in the pattern  A pattern matches a value, if the types agree (tuple matches tuple, list matches list, …) for tuples, the arity (number of fields must agree) the values agree  When a pattern matches, the variables are assigned to the matched values

Pattern Matching L02, ID1218, Christian Schulte 19  Can be used with the assignment operator =  For example {[X|Xr],4,{A,B}} = {[1],4,{b,a}} matches with X=1, Xr=[], A=b, B=a  But [] does not match [_|_], …

Single Assignment Variables  A variable can be assigned only to the same value X=[1,2],X=[1,2] otherwise runtime error  Major difference to Java, C, C++, … variables change over time also: stateful variables and programs  Single assignment variables simplify reasoning over programs concurrent programming L02, ID1218, Christian Schulte 20

Length of a List L02, ID1218, Christian Schulte 21  Inductive definition length of empty list is 0 length of cons is 1 + length of tail len([]) -> 0; len([_|Xr]) -> 1+len(Xr).

Case Expression len(Xs) -> case Xs of [] -> 0; [_|Xr] -> 1+len(Xr) end.  Like new function defined with several clauses  Functions with a single clause are sufficient  Scope rule: if variable X introduced in clause and used after end X must be introduced in all clauses L02, ID1218, Christian Schulte 22

If Expression fac(N) -> if N==0 -> 1; N>0 -> N*fac(N-1) end.  Scoping as with case L02, ID1218, Christian Schulte 23

Look Two: Summary L02, ID1218, Christian Schulte 24  List is either empty or cons with head and tail  List processing is recursive processing  Useful for this is pattern matching  Clauses can be replaced by case expression

A Third Look L02, ID1218, Christian Schulte

A Better Length? L02, ID1218, Christian Schulte 26 len(Xs) -> len(Xs,0). len([],N) -> N; len([_|Xr],N) -> len(Xr,N+1).  Two different functions: len/1 and len/2  Better, because much faster (but it has one more argument?) uses less memory (what memory? heap? stack?)

Appending Two Lists L02, ID1218, Christian Schulte 27 app([],Ys) -> Ys; app([X|Xr],Ys) -> [X|app(Xr,Ys)].  How much memory needed?  Stack space… in the length of the first list… Why?

Reversing a List L02, ID1218, Christian Schulte 28 rev([]) -> []; rev([X|Xr]) -> app(rev(Xr),[X]).  How much time needed? grows quadratic with the length of the input list… why? how can one find out?

Reversing a List: Better L02, ID1218, Christian Schulte 29 rev(Xs) -> rev(Xs,[]). rev([],Ys) -> Ys; rev([X|Xr],Ys) -> rev(Xr,[X|Ys]).  How much time needed? grows only linear with the length of the input list… how does this work? can we do that mechanically? The same as len/2 …

The MiniErlang Machine How Programs Compute L02, ID1218, Christian Schulte

Erlang Semantics  Semantics will define how programs compute operational semantics abstract machine (implementation blueprint)  Strategy define semantics for very simple Erlang programs captures the essence of how programs compute explains in particular how much stack space is needed L02, ID1218, Christian Schulte 31

The MiniErlang Machine  Executes MiniErlang programs  Uses two stacks expression stack: what needs to be evaluated value stack: was has already been evaluated  Starts with a single expression to be evaluated the value stack is empty  Finishes with a single value (the result) all expressions have been evaluated  Executes expressions and instructions instructions perform operations after all required arguments have been evaluated L02, ID1218, Christian Schulte 32

Roadmap: MiniErlang  What to compute with MiniErlang expressions and programs  What are the results MiniErlang Values  What are the instructions for compound value construction and function call  How are functions called parameters are passed by substitution considers only matching clauses clauses have patterns (we ignore guards) L02, ID1218, Christian Schulte 33

Evaluating Values L02, ID1218, Christian Schulte

MiniErlang Values  A MiniErlang value is an integer or a list other values are similar  In short notation V := int | [] | [ V 1 | V 2 ] known as BNF notation: discussed later so: values are referred to by V (possibly subscripted) can be: any integer, the empty list, a cons consisting of two values V 1 and V 2 L02, ID1218, Christian Schulte 35

MiniErlang Expressions  A MiniErlang expression is a value, a variable, or a function call E :=int | [] | [ E 1 | E 2 ] |X | F(E 1,…, E n ) expressions referred to by E variables referred to by X function names referred to by F L02, ID1218, Christian Schulte 36

MiniErlang Machine  MiniErlang machine Es ; Vs → Es’ ; Vs’ transforms a pair (separated by ;) of expression stack Es and value stack Vs into a new pair of expression stack Es’ and value stack Vs’  Initial configuration: expression we want to evaluate on expression stack  Final configuration: single value as result on value stack L02, ID1218, Christian Schulte 37

Stacks  We write stacks as X 1  …  X n  Xr top of stack X 1 n-th element X n more elementsXr empty stack   Pushing X to stack Xr: X  Xr  Popping X from stack X  Xr:Xr L02, ID1218, Christian Schulte 38

MiniErlang Execution Idea  Simple case: an integer evaluates to itself the result of an integer expression… …is an integer value  MiniErlang machine i  Er ; Vs → Er ; i  Vs if the expression stack has the integer i as top of stack… execution yields: the expression i is popped from the expression stack and pushed on to the value stack same for empty list L02, ID1218, Christian Schulte 39

MiniErlang Instruction Idea  How to evaluate a list expression [ E 1 | E 2 ] first evaluate E 1, to a value V 1, … then evaluate E 2, to a value V 2, … then construct a new value [ V 1 | V 2 ]  Use an instruction that says: build a list makes the assumption that values needed are on the value stack execution will pop two values, push a new list value when [ E 1 | E 2 ] is executed, E 1 and E 2 and the instruction CONS are pushed on the expression stack L02, ID1218, Christian Schulte 40

Evaluating a List Expression  Evaluate a list expression [ E 1 | E 2 ]  Er ; Vs → E 1  E 2  CONS  Er ; Vs  Execute a CONS instruction CONS  Er ; V 1  V 2  Vs → Er ; [ V 2 | V 1 ]  Vs L02, ID1218, Christian Schulte 41

Example  We want to evaluate the expression [1|[]] (that is, just the list [1] )  Start configuration of our machine [1|[]] ;  expression stack: [1|[]] empty value stack:   What should be the end configuration:  ; [1|[]] empty expression stack:  result on value stack: [1|[]] L02, ID1218, Christian Schulte 42

Let’s Do It! [1|[]] ;  → … L02, ID1218, Christian Schulte 43 [ E 1 | E 2 ]  Er ; Vs → E 1  E 2  CONS  Er ; Vs

Let’s Do It! [1|[]] ;  → 1  []  CONS ;  → … L02, ID1218, Christian Schulte 44 i  Er ; Vs → Er ; i  Vs

Let’s Do It! [1|[]] ;  → 1  []  CONS ;  → []  CONS ; 1 → … L02, ID1218, Christian Schulte 45 i  Er ; Vs → Er ; i  Vs

Let’s Do It! [1|[]] ;  → 1  []  CONS ;  → []  CONS ; 1 → CONS ; []  1 → … L02, ID1218, Christian Schulte 46 CONS  Er ; V 1  V 2  Vs → Er ; [ V 2 | V 1 ]  Vs

Let’s Do It! [1|[]] ;  → 1  []  CONS ;  → []  CONS ; 1 → CONS ; []  1 →  ; [1|[]] L02, ID1218, Christian Schulte 47

Summary  MiniErlang values expressions  MiniErlang machine operates on expression and value stack evaluates topmost expression on expr stack executes topmost instruction on expr stack  Start state: single expr on expr stack  Final state: single value on value stack L02, ID1218, Christian Schulte 48

Summary & Homework L02, ID1218, Christian Schulte

Summary: MiniErlang  Stack-based operational semantics expressions, values, patterns, substitutions, matching  What did we learn how to describe how programs compute semi-gentle introduction to semantics better understanding of Erlang programs blueprint of a stack-based implementation  What will we use it for tool for analyzing how Erlang programs compute L02, ID1218, Christian Schulte 50

Homework  Take some expressions execute them by hand L02, ID1218, Christian Schulte 51