51
FUNCTIONAL PROGRAMMING IN ERLANG ID1218 Lecture 02 2009-10-28 Christian Schulte [email protected] Software and Computer Systems School of Information and Communication Technology KTH – Royal Institute of Technology Stockholm, Sweden

Functional Programming in Erlang

  • Upload
    nolen

  • View
    48

  • Download
    2

Embed Size (px)

DESCRIPTION

Christian Schulte [email protected] Software and Computer Systems School of Information and Communication Technology KTH – Royal Institute of Technology Stockholm, Sweden. Functional Programming in Erlang. ID1218 Lecture 022009-10-28. Reminder & Overview. Functional Programming. - PowerPoint PPT Presentation

Citation preview

Page 1: Functional Programming in Erlang

FUNCTIONAL PROGRAMMING IN ERLANG

ID1218 Lecture 02 2009-10-28

Christian [email protected]

Software and Computer SystemsSchool of Information and Communication

TechnologyKTH – Royal Institute of Technology

Stockholm, Sweden

Page 2: Functional Programming in Erlang

Reminder & Overview

L02, 2008-10-29

2

ID1218, Christian Schulte

Page 3: Functional Programming in Erlang

Functional Programming

L02, 2008-10-29ID1218, Christian Schulte

3

Compute by evaluating functions returning results

Techniques recursion with last-call-optimization pattern matching list processing higher-order programming accumulators

Page 4: Functional Programming in Erlang

Functional Programming in Erlang

L02, 2008-10-29ID1218, 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

Page 5: Functional Programming in Erlang

Function Definition

L02, 2008-10-29ID1218, 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

Page 6: Functional Programming in Erlang

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, 2008-10-29ID1218, Christian Schulte

6

Page 7: Functional Programming in Erlang

Overview

L02, 2008-10-29ID1218, 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

Page 8: Functional Programming in Erlang

A Second Look

L02, 2008-10-29

8

ID1218, Christian Schulte

Page 9: Functional Programming in Erlang

Tuples

L02, 2008-10-29ID1218, Christian Schulte

9

Combine several values here: 1, a, 2 position is significant!

{1,a,2} {}

1 a 2

Page 10: Functional Programming in Erlang

Lists

L02, 2008-10-29ID1218, 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

Page 11: Functional Programming in Erlang

An Example List

L02, 2008-10-29ID1218, 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 []

Page 12: Functional Programming in Erlang

Head And Tail

L02, 2008-10-29ID1218, Christian Schulte

12

The head and tail can be accessed by builtin functions (BIFs) hd/1 and tl/1

hd([X|Xr]) evaluates to Xtl([X|Xr]) evaluates to Xr

Page 13: Functional Programming in Erlang

Example of Head and Tail

L02, 2008-10-29ID1218, 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!

Page 14: Functional Programming in Erlang

How to Process Lists

L02, 2008-10-29ID1218, 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))

Page 15: Functional Programming in Erlang

Sum of a List

L02, 2008-10-29ID1218, Christian Schulte

15

sum(Xs) when Xs==[] -> 0;sum(Xs) -> hd(Xs)+sum(tl(Xs)).

Page 16: Functional Programming in Erlang

General Method

L02, 2008-10-29ID1218, 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

Page 17: Functional Programming in Erlang

Sum with Pattern Matching

L02, 2008-10-29ID1218, Christian Schulte

17

sum([]) -> 0;sum([X|Xr]) -> X+sum(Xr).

Page 18: Functional Programming in Erlang

Pattern Matching

L02, 2008-10-29ID1218, 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

Page 19: Functional Programming in Erlang

Pattern Matching

L02, 2008-10-29ID1218, Christian Schulte

19

Can be used with the assignment operator =

For example{[X|Xr],4,{A,B}} = {[1],4,{b,a}}

matches withX=1, Xr=[], A=b, B=a

But [] does not match [_|_], …

Page 20: Functional Programming in Erlang

Single Assignment Variables A variable can be assigned only to the

same valueX=[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, 2008-10-29ID1218, Christian Schulte

20

Page 21: Functional Programming in Erlang

Length of a List

L02, 2008-10-29ID1218, 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).

Page 22: Functional Programming in Erlang

Case Expressionlen(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, 2008-10-29ID1218, Christian Schulte

22

Page 23: Functional Programming in Erlang

If Expressionfac(N) -> if N==0 -> 1; N>0 -> N*fac(N-1) end. Scoping as with case

L02, 2008-10-29ID1218, Christian Schulte

23

Page 24: Functional Programming in Erlang

Look Two: Summary

L02, 2008-10-29ID1218, 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

Page 25: Functional Programming in Erlang

A Third Look

L02, 2008-10-29

25

ID1218, Christian Schulte

Page 26: Functional Programming in Erlang

A Better Length?

L02, 2008-10-29ID1218, 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?)

Page 27: Functional Programming in Erlang

Appending Two Lists

L02, 2008-10-29ID1218, 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?

Page 28: Functional Programming in Erlang

Reversing a List

L02, 2008-10-29ID1218, 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?

Page 29: Functional Programming in Erlang

Reversing a List: Better

L02, 2008-10-29ID1218, 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…

Page 30: Functional Programming in Erlang

The MiniErlang Machine

How Programs Compute

L02, 2008-10-29

30

ID1218, Christian Schulte

Page 31: Functional Programming in Erlang

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

neededL02, 2008-10-29ID1218, Christian Schulte

31

Page 32: Functional Programming in Erlang

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, 2008-10-29ID1218, Christian Schulte

32

Page 33: Functional Programming in Erlang

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, 2008-10-29ID1218, Christian Schulte

33

Page 34: Functional Programming in Erlang

Evaluating Values

L02, 2008-10-29

34

ID1218, Christian Schulte

Page 35: Functional Programming in Erlang

MiniErlang Values A MiniErlang value is an integer or a list

other values are similar In short notation

V := int | [] | [ V1 | V2 ] 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 V1 and V2

L02, 2008-10-29ID1218, Christian Schulte

35

Page 36: Functional Programming in Erlang

MiniErlang Expressions A MiniErlang expression is a value, a

variable, or a function callE := int | [] | [ E1 |

E2 ] | X | F(E1,…, En)

expressions referred to by E variables referred to by X function names referred to by F

L02, 2008-10-29ID1218, Christian Schulte

36

Page 37: Functional Programming in Erlang

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, 2008-10-29ID1218, Christian Schulte

37

Page 38: Functional Programming in Erlang

Stacks We write stacks as

X1 … Xn Xr top of stack X1 n-th element Xn more elements Xr empty stack

Pushing X to stack Xr: X Xr Popping X from stack X Xr: Xr

L02, 2008-10-29ID1218, Christian Schulte

38

Page 39: Functional Programming in Erlang

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, 2008-10-29ID1218, Christian Schulte

39

Page 40: Functional Programming in Erlang

MiniErlang Instruction Idea How to evaluate a list expression [ E1 |

E2 ] first evaluate E1 , to a value V1, … then evaluate E2 , to a value V2, … then construct a new value [ V1 | V2 ]

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 [ E1 | E2 ] is executed, E1 and E2 and the

instruction CONS are pushed on the expression stack

L02, 2008-10-29ID1218, Christian Schulte

40

Page 41: Functional Programming in Erlang

Evaluating a List Expression Evaluate a list expression

[E1|E2]Er ; Vs→ E1E2CONSEr ; Vs

Execute a CONS instructionCONSEr ; V1V2Vs

→ Er ; [V2|V1]Vs

L02, 2008-10-29ID1218, Christian Schulte

41

Page 42: Functional Programming in Erlang

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, 2008-10-29ID1218, Christian Schulte

42

Page 43: Functional Programming in Erlang

Let’s Do It![1|[]] ;

→ …

L02, 2008-10-29ID1218, Christian Schulte

43

[E1|E2]Er ; Vs→ E1E2CONSEr ; Vs

Page 44: Functional Programming in Erlang

Let’s Do It![1|[]] ;

→ 1 []CONS ; → …

L02, 2008-10-29ID1218, Christian Schulte

44

i Er ; Vs → Er ; i Vs

Page 45: Functional Programming in Erlang

Let’s Do It![1|[]] ;

→ 1 []CONS ; → []CONS ; 1→ …

L02, 2008-10-29ID1218, Christian Schulte

45

i Er ; Vs → Er ; i Vs

Page 46: Functional Programming in Erlang

Let’s Do It![1|[]] ;

→ 1 []CONS ; → []CONS ; 1→ CONS ; []1→ …

L02, 2008-10-29ID1218, Christian Schulte

46

CONSEr ; V1V2Vs→ Er ; [V2|V1]Vs

Page 47: Functional Programming in Erlang

Let’s Do It![1|[]] ;

→ 1 []CONS ; → []CONS ; 1→ CONS ; []1→ ; [1|[]]

L02, 2008-10-29ID1218, Christian Schulte

47

Page 48: Functional Programming in Erlang

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, 2008-10-29ID1218, Christian Schulte

48

Page 49: Functional Programming in Erlang

Summary & Homework

L02, 2008-10-29

49

ID1218, Christian Schulte

Page 50: Functional Programming in Erlang

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, 2008-10-29ID1218, Christian Schulte

50

Page 51: Functional Programming in Erlang

Homework Take some expressions

execute them by hand

L02, 2008-10-29ID1218, Christian Schulte

51