Programming Languages (CSCI 4430/6430) Part 1: Functional Programming: Summary

Size: px
Start display at page:

Download "Programming Languages (CSCI 4430/6430) Part 1: Functional Programming: Summary"

Transcription

1 Programming Languages (CSCI 4430/6430) Part 1: Functional Programming: Summary Carlos Varela Rennselaer Polytechnic Institute September 29, 2017 C. Varela 1

2 Other programming languages Imperative Algol (Naur 1958) Cobol (Hopper 1959) BASIC (Kennedy and Kurtz 1964) Pascal (Wirth 1970) C (Kernighan and Ritchie 1971) Ada (Whitaker 1979) Functional ML (Milner 1973) Scheme (Sussman and Steele 1975) Haskell (Hughes et al 1987) Object-Oriented Smalltalk (Kay 1980) C++ (Stroustrop 1980) Eiffel (Meyer 1985) Java (Gosling 1994) C# (Hejlsberg 2000) Actor-Oriented Act (Lieberman 1981) ABCL (Yonezawa 1988) Actalk (Briot 1989) Erlang (Armstrong 1990) E (Miller et al 1998) SALSA (Varela and Agha 1999) Scripting Python (van Rossum 1985) Perl (Wall 1987) Tcl (Ousterhout 1988) Lua (Ierusalimschy et al 1994) JavaScript (Eich 1995) PHP (Lerdorf 1995) Ruby (Matsumoto 1995) C. Varela 2

3 Language syntax Defines what are the legal programs, i.e. programs that can be executed by a machine (interpreter) Syntax is defined by grammar rules A grammar defines how to make sentences out of words For programming languages: sentences are called statements (commands, expressions) For programming languages: words are called tokens Grammar rules are used to describe both tokens and statements C. Varela; Adapted w/permission from S. Haridi and P. Van Roy 3

4 Language Semantics Semantics defines what a program does when it executes Semantics should be simple and yet allows reasoning about programs (correctness, execution time, and memory use) C. Varela; Adapted w/permission from S. Haridi and P. Van Roy 4

5 Lambda Calculus Syntax and Semantics The syntax of a λ-calculus expression is as follows: e ::= v variable λv.e functional abstraction (e e) function application The semantics of a λ-calculus expression is called beta-reduction: (λx.e M) E{M/x} where we alpha-rename the lambda abstraction E if necessary to avoid capturing free variables in M. C. Varela 5

6 α-renaming Alpha renaming is used to prevent capturing free occurrences of variables when beta-reducing a lambda calculus expression. In the following, we rename x to z, (or any other fresh variable): (λx.(y x) x) α (λz.(y z) x) Only bound variables can be renamed. No free variables can be captured (become bound) in the process. For example, we cannot alpha-rename x to y. C. Varela 6

7 β-reduction (λx.e M) β E{M/x} Beta-reduction may require alpha renaming to prevent capturing free variable occurrences. For example: (λx.λy.(x y) (y w)) α β (λx.λz.(x z) (y w)) λz.((y w) z) Where the free y remains free. C. Varela 7

8 η-conversion λx.(e x) η E if x is not free in E. For example: (λx.λy.(x y) (y w)) α β η (λx.λz.(x z) (y w)) λz.((y w) z) (y w) C. Varela 8

9 Currying The lambda calculus can only represent functions of one variable. It turns out that one-variable functions are sufficient to represent multiple-variable functions, using a strategy called currying. E.g., given the mathematical function: h(x,y) = x+y of type h: Z x Z Z We can represent h as h of type: h : Z Z Z Such that h(x,y) = h (x)(y) = x+y For example, h (2) = g, where g(y) = 2+y We say that h is the curried version of h. C. Varela 9

10 Function Composition in Lambda Calculus S: λx.(s x) (Square) I: λx.(i x) (Increment) C: λf.λg.λx.(f (g x)) (Function Composition) Recall semantics rule: ((C S) I) (λx.e M) E{M/x} ((λf.λg.λx.(f (g x)) λx.(s x)) λx.(i x)) (λg.λx.(λx.(s x) (g x)) λx.(i x)) λx.(λx.(s x) (λx.(i x) x)) λx.(λx.(s x) (i x)) λx.(s (i x)) C. Varela 10

11 Order of Evaluation in the Lambda Calculus Does the order of evaluation change the final result? Consider: Recall semantics rule: λx.(λx.(s x) (λx.(i x) x)) (λx.e M) E{M/x} There are two possible evaluation orders: and: λx.(λx.(s x) (λx.(i x) x)) λx.(λx.(s x) (i x)) λx.(s (i x)) λx.(λx.(s x) (λx.(i x) x)) λx.(s (λx.(i x) x)) λx.(s (i x)) Applicative Order Normal Order Is the final result always the same? C. Varela 11

12 Church-Rosser Theorem If a lambda calculus expression can be evaluated in two different ways and both ways terminate, both ways will yield the same result. e e 1 e 2 e Also called the diamond or confluence property. Furthermore, if there is a way for an expression evaluation to terminate, using normal order will cause termination. C. Varela 12

13 Order of Evaluation and Termination Consider: (λx.y (λx.(x x) λx.(x x))) Recall semantics rule: There are two possible evaluation orders: (λx.e M) E{M/x} and: (λx.y (λx.(x x) λx.(x x))) (λx.y (λx.(x x) λx.(x x))) (λx.y (λx.(x x) λx.(x x))) y Applicative Order Normal Order In this example, normal order terminates whereas applicative order does not. C. Varela 13

14 Free and Bound Variables The lambda functional abstraction is the only syntactic construct that binds variables. That is, in an expression of the form: λv.e we say that free occurrences of variable v in expression e are bound. All other variable occurrences are said to be free. E.g., (λx.λy.(x y) (y w)) Bound Variables Free Variables C. Varela 14

15 Combinators A lambda calculus expression with no free variables is called a combinator. For example: I: λx.x (Identity) App: λf.λx.(f x) (Application) C: λf.λg.λx.(f (g x)) (Composition) L: (λx.(x x) λx.(x x)) (Loop) Cur: λf.λx.λy.((f x) y) (Currying) Seq: λx.λy.(λz.y x) (Sequencing--normal order) ASeq: λx.λy.(y x) (Sequencing--applicative order) where y denotes a thunk, i.e., a lambda abstraction wrapping the second expression to evaluate. The meaning of a combinator is always the same indepently of its context. C. Varela 15

16 Currying Combinator in Oz The currying combinator can be written in Oz as follows: fun {$ F} fun {$ X} fun {$ Y} {F X Y} It takes a function of two arguments, F, and returns its curried version, e.g., {{{Curry Plus} 2} 3} 5 C. Varela 16

17 Recursion Combinator (Y or rec) X can be defined as (Y f), where Y is the recursion combinator. Y: λf.(λx.(f λy.((x x) y)) λx.(f λy.((x x) y))) Y: λf.(λx.(f (x x)) λx.(f (x x))) Applicative Order Normal Order You get from the normal order to the applicative order recursion combinator by η-expansion (η-conversion from right to left). C. Varela 17

18 Natural Numbers in Lambda Calculus 0 : λx.x (Zero) 1 : λx.λx.x (One) n+1 : λx. n (N+1) s: λn.λx.n (Successor) (s 0) (λn.λx.n λx.x) Recall semantics rule: (λx.e M) E{M/x} λx.λx.x C. Varela 18

19 Booleans and Branching (if) in λ Calculus true : λx.λy.x (True) false : λx.λy.y (False) if : λb.λt.λe.((b t) e) (If) Recall semantics rule: (((if true) a) b) (λx.e M) E{M/x} (((λb.λt.λe.((b t) e) λx.λy.x) a) b) ((λt.λe.((λx.λy.x t) e) a) b) (λe.((λx.λy.x a) e) b) ((λx.λy.x a) b) (λy.a b) a C. Varela 19

20 Church Numerals 0 : λf.λx.x (Zero) 1 : λf.λx.(f x) (One) n : λf.λx.(f (f x) ) (N applications of f to x) s: λn.λf.λx.(f ((n f) x)) (Successor) Recall semantics rule: (s 0) (λx.e M) E{M/x} (λn.λf.λx.(f ((n f) x)) λf.λx.x) λf.λx.(f ((λf.λx.x f) x)) λf.λx.(f (λx.x x)) λf.λx.(f x) C. Varela 20

21 Church Numerals: iszero? iszero?: λn.((n λx.false) true) (Is n=0?) (iszero? 0) (λn.((n λx.false) true) λf.λx.x) ((λf.λx.x λx.false) true) (λx.x true) true Recall semantics rule: (λx.e M) E{M/x} (iszero? 1) (λn.((n λx.false) true) λf.λx.(f x)) ((λf.λx.(f x) λx.false) true) (λx.(λx.false x) true) (λx.false true) false C. Varela 21

22 Functions Compute the factorial function: Start with the mathematical definition declare fun {Fact N} if N==0 then 1 else N*{Fact N-1} Fact is declared in the environment n! = 1 2 ( n 1) n 0! = 1 n! = n ( n 1)!if n > 0 Try large factorial {Browse {Fact 100}} C. Varela; Adapted w. permission from S. Haridi and P. Van Roy 22

23 Factorial in Haskell factorial :: Integer -> Integer factorial 0 = 1 factorial n n > 0 = n * factorial (n-1) C. Varela; Adapted w/permission from S. Haridi and P. Van Roy 23

24 Structured data (lists) Calculate Pascal triangle Write a function that calculates the nth row as one structured value A list is a sequence of elements: [ ] The empty list is written nil Lists are created by means of (cons) declare H=1 T = [ ] {Browse H T} % This will show [ ] C. Varela; Adapted w. permission from S. Haridi and P. Van Roy 24

25 Pattern matching Another way to take a list apart is by use of pattern matching with a case instruction case L of H T then {Browse H} {Browse T} else {Browse empty list } C. Varela; Adapted w. permission from S. Haridi and P. Van Roy 25

26 Functions over lists Compute the function {Pascal N} Takes an integer N, and returns the Nth row of a Pascal triangle as a list 1. For row 1, the result is [1] 2. For row N, shift to left row N-1 and shift to the right row N-1 3. Align and add the shifted rows element-wise to get row N (0) (0) Shift right [ ] Shift left [ ] C. Varela; Adapted w. permission from S. Haridi and P. Van Roy 26

27 Functions over lists Pascal N declare fun {Pascal N} if N==1 then [1] else {AddList {ShiftLeft {Pascal N-1}} {ShiftRight {Pascal N-1}}} Pascal N-1 Pascal N-1 ShiftLeft ShiftRight AddList C. Varela; Adapted w. permission from S. Haridi and P. Van Roy 27

28 Functions over lists (2) fun {ShiftLeft L} case L of H T then H {ShiftLeft T} else [0] fun {ShiftRight L} 0 L fun {AddList L1 L2} case L1 of H1 T1 then case L2 of H2 T2 then H1+H2 {AddList T1 T2} else nil C. Varela; Adapted w. permission from S. Haridi and P. Van Roy 28

29 Pattern matching in Haskell Another way to take a list apart is by use of pattern matching with a case instruction: case l of (h:t) -> h:t [] -> [] Or more typically as part of a function definition: id (h:t) -> h:t id [] -> [] C. Varela; Adapted w. permission from S. Haridi and P. Van Roy 29

30 Functions over lists in Haskell --- Pascal triangle row pascal :: Integer -> [Integer] pascal 1 = [1] pascal n = addlist (shiftleft (pascal (n-1))) where (shiftright (pascal (n-1))) shiftleft [] = [0] shiftleft (h:t) = h:shiftleft t shiftright l = 0:l addlist [] [] = [] addlist (h1:t1) (h2:t2) = (h1+h2):addlist t1 t2 C. Varela; Adapted w. permission from S. Haridi and P. Van Roy 30

31 Mathematical induction Select one or more inputs to the function Show the program is correct for the simple cases (base cases) Show that if the program is correct for a given case, it is then correct for the next case. For natural numbers, the base case is either 0 or 1, and for any number n the next case is n+1 For lists, the base case is nil, or a list with one or a few elements, and for any list T the next case is H T C. Varela; Adapted w. permission from S. Haridi and P. Van Roy 31

32 Correctness of factorial fun {Fact N} if N==0 then 1 else N*{Fact N-1} 1 2 n n ( 1) Fact( n 1) Base Case N=0: {Fact 0} returns 1 Inductive Case N>0: {Fact N} returns N*{Fact N-1} assume {Fact N-1} is correct, from the spec we see that {Fact N} is N*{Fact N-1} C. Varela; Adapted w. permission from S. Haridi and P. Van Roy 32

33 Iterative computation An iterative computation is one whose execution stack is bounded by a constant, indepent of the length of the computation Iterative computation starts with an initial state S 0, and transforms the state in a number of steps until a final state S final is reached: s s... s 0 1 final C. Varela; Adapted w/permission from S. Haridi and P. Van Roy 33

34 The general scheme fun {Iterate S i } if {IsDone S i } then S i else S i+1 in S i+1 = {Transform S i } {Iterate S i+1 } IsDone and Transform are problem depent C. Varela; Adapted w/permission from S. Haridi and P. Van Roy 34

35 From a general scheme to a control abstraction (2) fun {Iterate S IsDone Transform} if {IsDone S} then S else S1 in S1 = {Transform S} {Iterate S1 IsDone Transform} fun {Iterate S i } if {IsDone S i } then S i else S i+1 in S i+1 = {Transform S i } {Iterate S i+1 } C. Varela; Adapted w/permission from S. Haridi and P. Van Roy 35

36 Sqrt using the control abstraction fun {Sqrt X} {Iterate } 1.0 fun {$ G} {Abs X - G*G}/X < fun {$ G} (G + X/G)/2.0 Iterate could become a linguistic abstraction C. Varela; Adapted w/permission from S. Haridi and P. Van Roy 36

37 Sqrt in Haskell let sqrt x = head (dropwhile (not. goodenough) sqrtguesses) where goodenough guess = (abs (x guess*guess))/x < improve guess = (guess + x/guess)/2.0 sqrtguesses = 1:(map improve sqrtguesses) This sqrt example uses infinite lists enabled by lazy evaluation, and the map control abstraction. C. Varela; Adapted w/permission from S. Haridi and P. Van Roy 37

38 Higher-order programming Higher-order programming = the set of programming techniques that are possible with procedure values (lexically-scoped closures) Basic operations Procedural abstraction: creating procedure values with lexical scoping Genericity: procedure values as arguments Instantiation: procedure values as return values Embedding: procedure values in data structures Higher-order programming is the foundation of component-based programming and object-oriented programming C. Varela; Adapted w/permission from S. Haridi and P. Van Roy 38

39 Procedural abstraction Procedural abstraction is the ability to convert any statement into a procedure value A procedure value is usually called a closure, or more precisely, a lexically-scoped closure A procedure value is a pair: it combines the procedure code with the environment where the procedure was created (the contextual environment) Basic scheme: Consider any statement <s> Convert it into a procedure value: P = proc {$} <s> Executing {P} has exactly the same effect as executing <s> C. Varela; Adapted w/permission from S. Haridi and P. Van Roy 39

40 Procedure values Constructing a procedure value in the store is not simple because a procedure may have external references local P Q in P = proc {$ } {Q } Q = proc {$ } {Browse hello} local Q in Q = proc {$ } {Browse hi} {P } S. Haridi and P. Van Roy 40

41 Procedure values (2) P x 1 (, ) local P Q in P = proc {$ } {Q } Q = proc {$ } {Browse hello} local Q in Q = proc {$ } {Browse hi} {P } proc {$ } {Q } Q x 2 x 2 (, ) proc {$ } {Browse hello} Browse x 0 S. Haridi and P. Van Roy 41

42 Genericity Replace specific entities (zero 0 and addition +) by function arguments The same routine can do the sum, the product, the logical or, etc. fun {SumList L} case L of nil then 0 [] X L2 then X+{SumList L2} fun {FoldR L F U} case L of nil then U [] X L2 then {F X {FoldR L2 F U}} C. Varela; Adapted w/permission from S. Haridi and P. Van Roy 42

43 Genericity in Haskell Replace specific entities (zero 0 and addition +) by function arguments The same routine can do the sum, the product, the logical or, etc. sumlist :: (Num a) => [a] -> a sumlist [] = 0 sumlist (h:t) = h+sumlist t foldr' :: (a->b->b) -> b -> [a] -> b foldr' _ u [] = u foldr' f u (h:t) = f h (foldr' f u t) C. Varela; Adapted w/permission from S. Haridi and P. Van Roy 43

44 Instantiation fun {FoldFactory F U} fun {FoldR L} case L of nil then U [] X L2 then {F X {FoldR L2}} in FoldR Instantiation is when a procedure returns a procedure value as its result Calling {FoldFactory fun {$ A B} A+B 0} returns a function that behaves identically to SumList, which is an «instance» of a folding function C. Varela; Adapted w/permission from S. Haridi and P. Van Roy 44

45 Embedding Embedding is when procedure values are put in data structures Embedding has many uses: Modules: a module is a record that groups together a set of related operations Software components: a software component is a generic function that takes a set of modules as its arguments and returns a new module. It can be seen as specifying a module in terms of the modules it needs. Delayed evaluation (also called explicit lazy evaluation): build just a small part of a data structure, with functions at the extremities that can be called to build more. The consumer can control explicitly how much of the data structure is built. C. Varela; Adapted w/permission from S. Haridi and P. Van Roy 45

46 Control Abstractions fun {FoldL Xs F U} case Xs of nil then U [] X Xr then {FoldL Xr F {F X U}} What does this program do? {Browse {FoldL [1 2 3] fun {$ X Y} X Y nil}} C. Varela; Adapted w/permission from S. Haridi and P. Van Roy 46

47 FoldL in Haskell foldl' :: (b->a->b) -> b -> [a] -> b foldl' _ u [] = u foldl' f u (h:t) = foldl' f (f u h) t Notice the unit u is of type b, and the function f is of type b->a->b. C. Varela; Adapted w/permission from S. Haridi and P. Van Roy 47

48 List-based techniques fun {Map Xs F} case Xs of nil then nil [] X Xr then {F X} {Map Xr F} fun {Filter Xs P} case Xs of nil then nil [] X Xr andthen {P X} then X {Filter Xr P} [] X Xr then {Filter Xr P} C. Varela; Adapted w/permission from S. Haridi and P. Van Roy 48

49 Map in Haskell map' :: (a -> b) -> [a] -> [b] map' _ [] = [] map' f (h:t) = f h:map' f t _ means that the argument is not used (read don t care ). map is to distinguish it from the Prelude map function. C. Varela; Adapted w/permission from S. Haridi and P. Van Roy 49

50 Filter in Haskell filter' :: (a-> Bool) -> [a] -> [a] filter' _ [] = [] filter' p (h:t) = if p h then h:filter' p t else filter' p t C. Varela; Adapted w/permission from S. Haridi and P. Van Roy 50

51 Filter as FoldR application fun {Filter L P} {FoldR L fun {$ H T} if {P H} then H T else T nil} filter'' :: (a-> Bool) -> [a] -> [a] filter'' p l = foldr (\h t -> if p h then h:t else t) [] l C. Varela; Adapted w/permission from S. Haridi and P. Van Roy 51

52 Lazy evaluation The functions written so far are evaluated eagerly (as soon as they are called) Another way is lazy evaluation where a computation is done only when the results is needed Calculates the infinite list: declare fun lazy {Ints N} N {Ints N+1} C. Varela; Adapted from S. Haridi and P. Van Roy 52

53 Lazy evaluation (2) Write a function that computes as many rows of Pascal s triangle as needed We do not know how many beforehand A function is lazy if it is evaluated only when its result is needed The function PascalList is evaluated when needed fun lazy {PascalList Row} Row {PascalList {AddList {ShiftLeft Row} {ShiftRight Row}}} C. Varela; Adapted from S. Haridi and P. Van Roy 53

54 Larger Example: The Sieve of Eratosthenes Produces prime numbers It takes a stream 2...N, peals off 2 from the rest of the stream Delivers the rest to the next sieve Sieve Xs X X Zs Xr Filter Ys Sieve Zs C. Varela; Adapted from S. Haridi and P. Van Roy 54

55 Lazy Sieve fun lazy {Sieve Xs} X Xr = Xs in X {Sieve {LFilter Xr fun {$ Y} Y mod X \= 0 }} fun {Primes} {Sieve {Ints 2}} C. Varela; Adapted from S. Haridi and P. Van Roy 55

56 Lazy Filter For the Sieve program we need a lazy filter fun lazy {LFilter Xs F} case Xs of nil then nil [] X Xr then if {F X} then X {LFilter Xr F} else {LFilter Xr F} C. Varela; Adapted from S. Haridi and P. Van Roy 56

57 Primes in Haskell ints :: (Num a) => a -> [a] ints n = n : ints (n+1) sieve :: (Integral a) => [a] -> [a] sieve (x:xr) = x:sieve (filter (\y -> (y `mod` x /= 0)) xr) primes :: (Integral a) => [a] primes = sieve (ints 2) Functions in Haskell are lazy by default. You can use take 20 primes to get the first 20 elements of the list. C. Varela 57

58 List Comprehensions Abstraction provided in lazy functional languages that allows writing higher level set-like expressions In our context we produce lazy lists instead of sets The mathematical set expression {x*y 1 x 10, 1 y x} Equivalent List comprehension expression is [X*Y X = ; Y = 1..X] Example: [1*1 2*1 2*2 3*1 3*2 3* *10] C. Varela; Adapted from S. Haridi and P. Van Roy 58

59 List Comprehensions The general form is [ f(x,y,...,z) x gen(a1,...,an) ; guard(x,...) y gen(x, a1,...,an) ; guard(y,x,...)... ] No linguistic support in Mozart/Oz, but can be easily expressed C. Varela; Adapted from S. Haridi and P. Van Roy 59

60 Example 1 z = [x#x x from(1,10)] Z = {LMap {LFrom 1 10} fun{$ X} X#X } z = [x#y x from(1,10), y from(1,x)] Z = {LFlatten {LMap {LFrom 1 10} fun{$ X} {LMap {LFrom 1 X} fun {$ Y} X#Y } } } C. Varela; Adapted from S. Haridi and P. Van Roy 60

61 Example 2 z = [x#y x from(1,10), y from(1,x), x+y 10] Z ={LFilter {LFlatten {LMap {LFrom 1 10} fun{$ X} {LMap {LFrom 1 X} fun {$ Y} X#Y } } } fun {$ X#Y} X+Y=<10 } } C. Varela; Adapted from S. Haridi and P. Van Roy 61

62 List Comprehensions in Haskell lc1 = [(x,y) x <- [1..10], y <- [1..x]] lc2 = filter (\(x,y)->(x+y<=10)) lc1 lc3 = [(x,y) x <- [1..10], y <- [1..x], x+y<= 10] Haskell provides syntactic support for list comprehensions. List comprehensions are implemented using a built-in list monad. C. Varela 62

63 Quicksort using list comprehensions quicksort :: (Ord a) => [a] -> [a] quicksort [] = [] quicksort (h:t) = quicksort [x x <- t, x < h] ++ [h] ++ quicksort [x x <-t, x >= h] C. Varela 63

64 Types of typing Languages can be weakly typed Internal representation of types can be manipulated by a program e.g., a string in C is an array of characters ing in \0. Strongly typed programming languages can be further subdivided into: Dynamically typed languages Variables can be bound to entities of any type, so in general the type is only known at run-time, e.g., Oz, SALSA. Statically typed languages Variable types are known at compile-time, e.g., C++, Java. C. Varela 64

65 Type Checking and Inference Type checking is the process of ensuring a program is welltyped. One strategy often used is abstract interpretation: The principle of getting partial information about the answers from partial information about the inputs Programmer supplies types of variables and type-checker deduces types of other expressions for consistency Type inference frees programmers from annotating variable types: types are inferred from variable usage, e.g. ML, Haskell. C. Varela 65

66 Abstract data types A datatype is a set of values and an associated set of operations A datatype is abstract only if it is completely described by its set of operations regardless of its implementation This means that it is possible to change the implementation of the datatype without changing its use The datatype is thus described by a set of procedures These operations are the only thing that a user of the abstraction can assume C. Varela; Adapted w/permission from S. Haridi and P. Van Roy 66

67 Example: A Stack Assume we want to define a new datatype stack T whose elements are of any type T fun {NewStack}: Stack T fun {Push Stack T T }: Stack T fun {Pop Stack T T }: Stack T fun {IsEmpty Stack T }: Bool These operations normally satisfy certain laws: {IsEmpty {NewStack}} = true for any E and S0, S1={Push S0 E} and S0 ={Pop S1 E} hold {Pop {NewStack} E} raises error C. Varela; Adapted w/permission from S. Haridi and P. Van Roy 67

68 Stack (another implementation) fun {NewStack} nil fun {Push S E} E S fun {Pop S E} case S of X S1 then E = X S1 fun {IsEmpty S} S==nil fun {NewStack} emptystack fun {Push S E} stack(e S) fun {Pop S E} case S of stack(x S1) then E = X S1 fun {IsEmpty S} S==emptyStack C. Varela; Adapted w/permission from S. Haridi and P. Van Roy 68

69 Stack data type in Haskell data Stack a = Empty Stack a (Stack a) newstack :: Stack a newstack = Empty push :: Stack a -> a -> Stack a push s e = Stack e s pop :: Stack a -> (Stack a,a) pop (Stack e s) = (s,e) isempty :: Stack a -> Bool isempty Empty = True isempty (Stack ) = False C. Varela 69

70 Secure abstract data types: A secure stack With the wrapper & unwrapper we can build a secure stack local Wrap Unwrap in {NewWrapper Wrap Unwrap} fun {NewStack} {Wrap nil} fun {Push S E} {Wrap E {Unwrap S}} fun {Pop S E} case {Unwrap S} of X S1 then E=X {Wrap S1} fun {IsEmpty S} {Unwrap S}==nil proc {NewWrapper?Wrap?Unwrap} Key={NewName} in fun {Wrap X} fun {$ K} if K==Key then X fun {Unwrap C} {C Key} C. Varela; Adapted w/permission from S. Haridi and P. Van Roy 70

71 Stack abstract data type as a module in Haskell module StackADT (Stack,newStack,push,pop,isEmpty) where data Stack a = Empty Stack a (Stack a) newstack = Empty Modules can then be imported by other modules, e.g.: module Main (main) where import StackADT ( Stack, newstack,push,pop,isempty ) main = do print (push (push newstack 1) 2) C. Varela 71

72 Declarative operations (1) An operation is declarative if whenever it is called with the same arguments, it returns the same results indepent of any other computation state A declarative operation is: Indepent (deps only on its arguments, nothing else) Stateless (no internal state is remembered between calls) Deterministic (call with same operations always give same results) Declarative operations can be composed together to yield other declarative components All basic operations of the declarative model are declarative and combining them always gives declarative components C. Varela; Adapted w/permission from S. Haridi and P. Van Roy 72

73 Why declarative components (1) There are two reasons why they are important: (Programming in the large) A declarative component can be written, tested, and proved correct indepent of other components and of its own past history. The complexity (reasoning complexity) of a program composed of declarative components is the sum of the complexity of the components In general the reasoning complexity of programs that are composed of nondeclarative components explodes because of the intimate interaction between components (Programming in the small) Programs written in the declarative model are much easier to reason about than programs written in more expressive models (e.g., an object-oriented model). Simple algebraic and logical reasoning techniques can be used C. Varela; Adapted w/permission from S. Haridi and P. Van Roy 73

74 Monads Purely functional programming is declarative in nature: whenever a function is called with the same arguments, it returns the same results indepent of any other computation state. How to model the real world (that may have context depences, state, nondeterminism) in a purely functional programming language? Context depences: e.g., does file exist in expected directory? State: e.g., is there money in the bank account? Nondeterminism: e.g., does bank account deposit happen before or after interest accrual? Monads to the rescue! C. Varela 74

75 Monad class The Monad class defines two basic operations: class Monad m where (>>=) :: m a -> (a -> m b) -> m b -- bind return fail m >> k :: a -> m a :: String -> m a = m >>= \_ -> k The >>= infix operation binds two monadic values, while the return operation injects a value into the monad (container). Example monadic classes are IO, lists ([]) and Maybe. C. Varela 75

76 do syntactic sugar In the IO class, x >>= y, performs two actions sequentially (like the Seq combinator in the lambda-calculus) passing the result of the first into the second. Chains of monadic operations can use do: do e1 ; e2 = e1 >> e2 do p <- e1; e2 = e1 >>= \p -> e2 Pattern match can fail, so the full translation is: do p <- e1; e2 = e1 >>= (\v -> case of p -> e2 _ -> fail s ) Failure in IO monad produces an error, whereas failure in the List monad produces the empty list. C. Varela 76

77 Monad class laws All instances of the Monad class should respect the following laws: return a >>= k = k a m >>= return = m xs >>= return. f = fmap f xs m >>= (\x -> k x >>= h) = (m >>= k) >>= h These laws ensure that we can bind together monadic values with >>= and inject values into the monad (container) using return in consistent ways. The MonadPlus class includes an mzero element and an mplus operation. For lists, mzero is the empty list ([]), and the mplus operation is list concatenation (++). C. Varela 77

78 List comprehensions with monads lc1 = [(x,y) x <- [1..10], y <- [1..x]] lc1' = do x <- [1..10] y <- [1..x] return (x,y) lc1'' = [1..10] >>= (\x -> [1..x] >>= (\y -> return (x,y))) List comprehensions are implemented using a built-in list monad. Binding (l >>= f) applies the function f to all the elements of the list l and concatenates the results. The return function creates a singleton list. C. Varela 78

79 List comprehensions with monads (2) lc3 = [(x,y) x <- [1..10], y <- [1..x], x+y<= 10] lc3' = do x <- [1..10] y <- [1..x] True <- return (x+y<=10) return (x,y) lc3'' = [1..10] >>= (\x -> [1..x] >>= (\y -> return (x+y<=10) >>= Guards in list comprehensions assume that fail in the List monad returns an empty list. (\b -> case b of True -> return (x,y); _ -> fail ""))) C. Varela 79

80 Monads summary Monads enable keeping track of imperative features (state) in a way that is modular with purely functional components. For example, fib remains functional, yet the R monad enables us to keep a count of instructions separately. Input/output, list comprehensions, and optional values (Maybe class) are built-in monads in Haskell. Monads are useful to modularly define semantics of domain-specific languages. C. Varela 80

Programming Languages (CSCI 4430/6430) History, Syntax, Semantics, Essentials, Paradigms

Programming Languages (CSCI 4430/6430) History, Syntax, Semantics, Essentials, Paradigms Programming Languages (CSCI 4430/6430) History, Syntax, Semantics, Essentials, Paradigms Carlos Varela Rennselaer Polytechnic Institute August 30, 2016 C. Varela 1 The first programmer ever Ada Augusta,

More information

Lambda Calculus alpha-renaming, beta reduction, applicative and normal evaluation orders, Church-Rosser theorem, combinators

Lambda Calculus alpha-renaming, beta reduction, applicative and normal evaluation orders, Church-Rosser theorem, combinators Lambda Calculus alpha-renaming, beta reduction, applicative and normal evaluation orders, Church-Rosser theorem, combinators Carlos Varela Rennselaer Polytechnic Institute February 11, 2010 C. Varela 1

More information

CSCI.4430/6969 Programming Languages Lecture Notes

CSCI.4430/6969 Programming Languages Lecture Notes CSCI.4430/6969 Programming Languages Lecture Notes August 28, 2006 1 Brief History of Programming Languages Ada Augusta, the Countess of Lovelace, the daughter of the poet Lord Byron, is attributed as

More information

Types in Programming Languages Dynamic and Static Typing, Type Inference (CTM 2.8.3, EPL* 4) Abstract Data Types (CTM 3.7) Monads (GIH** 9)

Types in Programming Languages Dynamic and Static Typing, Type Inference (CTM 2.8.3, EPL* 4) Abstract Data Types (CTM 3.7) Monads (GIH** 9) Types in Programming Languages Dynamic and Static Typing, Type Inference (CTM 2.8.3, EPL* 4) Abstract Data Types (CTM 3.7) Monads (GIH** 9) Carlos Varela Rensselaer Polytechnic Institute September 23,

More information

Declarative Programming Techniques

Declarative Programming Techniques Declarative Programming Techniques Declarativeness, iterative computation (CTM 3.1-3.2) Higher-order programming (CTM 3.6) Abstract data types (CTM 3.7) Carlos Varela Rensselaer Polytechnic Institute April

More information

Carlos Varela RPI September 19, Adapted with permission from: Seif Haridi KTH Peter Van Roy UCL

Carlos Varela RPI September 19, Adapted with permission from: Seif Haridi KTH Peter Van Roy UCL Higher-Order Programming: Closures, procedural abstraction, genericity, instantiation, embedding. Control abstractions: iterate, map, reduce, fold, filter (CTM Sections 1.9, 3.6, 4.7) Carlos Varela RPI

More information

Lazy evaluation. Lazy evaluation (3) Lazy evaluation (2) Lazy execution. Example. Declarative Concurrency. Lazy Execution (VRH 4.

Lazy evaluation. Lazy evaluation (3) Lazy evaluation (2) Lazy execution. Example. Declarative Concurrency. Lazy Execution (VRH 4. Declarative Concurrency Lazy Execution (VRH 4.5) Carlos Varela RPI Lazy evaluation The deault unctions in Oz are evaluated eagerly (as soon as they are called) Another way is lazy evaluation where a computation

More information

State, Object-Oriented Programming Explicit State, Polymorphism (CTM ) Objects, Classes, and Inheritance (CTM )

State, Object-Oriented Programming Explicit State, Polymorphism (CTM ) Objects, Classes, and Inheritance (CTM ) State, Object-Oriented Programming Explicit State, Polymorphism (CTM 6.1-6.4.4) Objects, Classes, and Inheritance (CTM 7.1-7.2) Carlos Varela Rensselaer Polytechnic Institute October 27, 2017 Adapted with

More information

CMSC 330: Organization of Programming Languages

CMSC 330: Organization of Programming Languages CMSC 330: Organization of Programming Languages Lambda Calculus CMSC 330 1 Programming Language Features Many features exist simply for convenience Multi-argument functions foo ( a, b, c ) Use currying

More information

Programming Language Features. CMSC 330: Organization of Programming Languages. Turing Completeness. Turing Machine.

Programming Language Features. CMSC 330: Organization of Programming Languages. Turing Completeness. Turing Machine. CMSC 330: Organization of Programming Languages Lambda Calculus Programming Language Features Many features exist simply for convenience Multi-argument functions foo ( a, b, c ) Ø Use currying or tuples

More information

CMSC 330: Organization of Programming Languages

CMSC 330: Organization of Programming Languages CMSC 330: Organization of Programming Languages Lambda Calculus CMSC 330 1 Programming Language Features Many features exist simply for convenience Multi-argument functions foo ( a, b, c ) Ø Use currying

More information

CMSC330. Objects, Functional Programming, and lambda calculus

CMSC330. Objects, Functional Programming, and lambda calculus CMSC330 Objects, Functional Programming, and lambda calculus 1 OOP vs. FP Object-oriented programming (OOP) Computation as interactions between objects Objects encapsulate mutable data (state) Accessed

More information

n n Try tutorial on front page to get started! n spring13/ n Stack Overflow!

n   n Try tutorial on front page to get started! n   spring13/ n Stack Overflow! Announcements n Rainbow grades: HW1-6, Quiz1-5, Exam1 n Still grading: HW7, Quiz6, Exam2 Intro to Haskell n HW8 due today n HW9, Haskell, out tonight, due Nov. 16 th n Individual assignment n Start early!

More information

Lecture 5: The Untyped λ-calculus

Lecture 5: The Untyped λ-calculus Lecture 5: The Untyped λ-calculus Syntax and basic examples Polyvios Pratikakis Computer Science Department, University of Crete Type Systems and Static Analysis Pratikakis (CSD) Untyped λ-calculus I CS49040,

More information

CMSC 330: Organization of Programming Languages. Lambda Calculus

CMSC 330: Organization of Programming Languages. Lambda Calculus CMSC 330: Organization of Programming Languages Lambda Calculus 1 Turing Completeness Turing machines are the most powerful description of computation possible They define the Turing-computable functions

More information

COMP 1130 Lambda Calculus. based on slides by Jeff Foster, U Maryland

COMP 1130 Lambda Calculus. based on slides by Jeff Foster, U Maryland COMP 1130 Lambda Calculus based on slides by Jeff Foster, U Maryland Motivation Commonly-used programming languages are large and complex ANSI C99 standard: 538 pages ANSI C++ standard: 714 pages Java

More information

5. Introduction to the Lambda Calculus. Oscar Nierstrasz

5. Introduction to the Lambda Calculus. Oscar Nierstrasz 5. Introduction to the Lambda Calculus Oscar Nierstrasz Roadmap > What is Computability? Church s Thesis > Lambda Calculus operational semantics > The Church-Rosser Property > Modelling basic programming

More information

CMSC 330: Organization of Programming Languages. Lambda Calculus

CMSC 330: Organization of Programming Languages. Lambda Calculus CMSC 330: Organization of Programming Languages Lambda Calculus 1 100 years ago Albert Einstein proposed special theory of relativity in 1905 In the paper On the Electrodynamics of Moving Bodies 2 Prioritätsstreit,

More information

Lambda Calculus and Type Inference

Lambda Calculus and Type Inference Lambda Calculus and Type Inference Björn Lisper Dept. of Computer Science and Engineering Mälardalen University bjorn.lisper@mdh.se http://www.idt.mdh.se/ blr/ August 17, 2007 Lambda Calculus and Type

More information

Introduction to the λ-calculus

Introduction to the λ-calculus Announcements Prelim #2 issues: o Problem 5 grading guide out shortly o Problem 3 (hashing) issues Will be on final! Friday RDZ office hours are 11-12 not 1:30-2:30 1 Introduction to the λ-calculus Today

More information

Declarative Concurrency (CTM 4)

Declarative Concurrency (CTM 4) Declarative Concurrency (CTM 4) Carlos Varela Rensselaer Polytechnic Institute Adapted with permission from: Seif Haridi KTH Peter Van Roy UCL November 21, 2014 C. Varela; Adapted with permission from

More information

CMSC 330: Organization of Programming Languages

CMSC 330: Organization of Programming Languages CMSC 330: Organization of Programming Languages Lambda Calculus CMSC 330 Summer 2017 1 100 years ago Albert Einstein proposed special theory of relativity in 1905 In the paper On the Electrodynamics of

More information

On Academic Dishonesty. Declarative Computation Model. Single assignment store. Single assignment store (2) Single assignment store (3)

On Academic Dishonesty. Declarative Computation Model. Single assignment store. Single assignment store (2) Single assignment store (3) Declarative Computation Model Single assignment store (VRH 2.2) Kernel language syntax (VRH 2.3) Carlos Varela RPI October 6, 2009 Adapted with permission from: Seif Haridi KTH Peter Van Roy UCL On Academic

More information

CS 11 Haskell track: lecture 1

CS 11 Haskell track: lecture 1 CS 11 Haskell track: lecture 1 This week: Introduction/motivation/pep talk Basics of Haskell Prerequisite Knowledge of basic functional programming e.g. Scheme, Ocaml, Erlang CS 1, CS 4 "permission of

More information

Programming Language Concepts, CS2104 Lecture 7

Programming Language Concepts, CS2104 Lecture 7 Reminder of Last Lecture Programming Language Concepts, CS2104 Lecture 7 Tupled Recursion Exceptions Types, ADT, Haskell, Components 5th Oct 2007 CS2104, Lecture 7 1 Overview 5th Oct 2007 CS2104, Lecture

More information

Formal Semantics. Aspects to formalize. Lambda calculus. Approach

Formal Semantics. Aspects to formalize. Lambda calculus. Approach Formal Semantics Aspects to formalize Why formalize? some language features are tricky, e.g. generalizable type variables, nested functions some features have subtle interactions, e.g. polymorphism and

More information

CMSC 330: Organization of Programming Languages

CMSC 330: Organization of Programming Languages CMSC 330: Organization of Programming Languages Lambda Calculus Encodings CMSC 330 Spring 2017 1 Review A lambda calculus expression is defined as e ::= x variable λx.e abstraction (fun def) e e application

More information

COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen

COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen COP4020 Programming Languages Functional Programming Prof. Robert van Engelen Overview What is functional programming? Historical origins of functional programming Functional programming today Concepts

More information

Fundamentals and lambda calculus

Fundamentals and lambda calculus Fundamentals and lambda calculus Again: JavaScript functions JavaScript functions are first-class Syntax is a bit ugly/terse when you want to use functions as values; recall block scoping: (function ()

More information

λ-calculus Lecture 1 Venanzio Capretta MGS Nottingham

λ-calculus Lecture 1 Venanzio Capretta MGS Nottingham λ-calculus Lecture 1 Venanzio Capretta MGS 2018 - Nottingham Table of contents 1. History of λ-calculus 2. Definition of λ-calculus 3. Data Structures 1 History of λ-calculus Hilbert s Program David Hilbert

More information

Lambda Calculus and Extensions as Foundation of Functional Programming

Lambda Calculus and Extensions as Foundation of Functional Programming Lambda Calculus and Extensions as Foundation of Functional Programming David Sabel and Manfred Schmidt-Schauß 29. September 2015 Lehrerbildungsforum Informatik Last update: 30. September 2015 Overview

More information

Declarative Concurrency (CTM 4)

Declarative Concurrency (CTM 4) Declarative Concurrency (CTM 4) Carlos Varela Rensselaer Polytechnic Institute Adapted with permission from: Seif Haridi KTH Peter Van Roy UCL October 30, 2015 C. Varela; Adapted with permission from S.

More information

Pure (Untyped) λ-calculus. Andrey Kruglyak, 2010

Pure (Untyped) λ-calculus. Andrey Kruglyak, 2010 Pure (Untyped) λ-calculus Andrey Kruglyak, 2010 1 Pure (untyped) λ-calculus An example of a simple formal language Invented by Alonzo Church (1936) Used as a core language (a calculus capturing the essential

More information

CSC312 Principles of Programming Languages : Functional Programming Language. Copyright 2006 The McGraw-Hill Companies, Inc.

CSC312 Principles of Programming Languages : Functional Programming Language. Copyright 2006 The McGraw-Hill Companies, Inc. CSC312 Principles of Programming Languages : Functional Programming Language Overview of Functional Languages They emerged in the 1960 s with Lisp Functional programming mirrors mathematical functions:

More information

CMSC 330: Organization of Programming Languages. Formal Semantics of a Prog. Lang. Specifying Syntax, Semantics

CMSC 330: Organization of Programming Languages. Formal Semantics of a Prog. Lang. Specifying Syntax, Semantics Recall Architecture of Compilers, Interpreters CMSC 330: Organization of Programming Languages Source Scanner Parser Static Analyzer Operational Semantics Intermediate Representation Front End Back End

More information

Functional Programming and Haskell

Functional Programming and Haskell Functional Programming and Haskell Tim Dawborn University of Sydney, Australia School of Information Technologies Tim Dawborn Functional Programming and Haskell 1/22 What are Programming Paradigms? A programming

More information

CSCE 314 TAMU Fall CSCE 314: Programming Languages Dr. Flemming Andersen. Haskell Functions

CSCE 314 TAMU Fall CSCE 314: Programming Languages Dr. Flemming Andersen. Haskell Functions 1 CSCE 314: Programming Languages Dr. Flemming Andersen Haskell Functions 2 Outline Defining Functions List Comprehensions Recursion 3 Conditional Expressions As in most programming languages, functions

More information

CSCE 314 Programming Languages

CSCE 314 Programming Languages CSCE 314 Programming Languages Final Review Part I Dr. Hyunyoung Lee 1 Programming Language Characteristics Different approaches to describe computations, to instruct computing devices E.g., Imperative,

More information

Recursive Definitions, Fixed Points and the Combinator

Recursive Definitions, Fixed Points and the Combinator Recursive Definitions, Fixed Points and the Combinator Dr. Greg Lavender Department of Computer Sciences University of Texas at Austin Recursive Self-Reference Recursive self-reference occurs regularly

More information

10.6 Theoretical Foundations

10.6 Theoretical Foundations 10 Functional Languages 10.6 Theoretical Foundations EXAMPLE 10.44 Functions as mappings Mathematically,a function is a single-valued mapping: it associates every element in one set (the domain) with (at

More information

Programming Language Concepts, cs2104 Lecture 04 ( )

Programming Language Concepts, cs2104 Lecture 04 ( ) Programming Language Concepts, cs2104 Lecture 04 (2003-08-29) Seif Haridi Department of Computer Science, NUS haridi@comp.nus.edu.sg 2003-09-05 S. Haridi, CS2104, L04 (slides: C. Schulte, S. Haridi) 1

More information

Fundamentals and lambda calculus. Deian Stefan (adopted from my & Edward Yang s CSE242 slides)

Fundamentals and lambda calculus. Deian Stefan (adopted from my & Edward Yang s CSE242 slides) Fundamentals and lambda calculus Deian Stefan (adopted from my & Edward Yang s CSE242 slides) Logistics Assignments: Programming assignment 1 is out Homework 1 will be released tomorrow night Podcasting:

More information

Declarative Computation Model

Declarative Computation Model Declarative Computation Model Kernel language semantics revisited (VRH 2.4.5) From kernel to practical language (VRH 2.6) Exceptions (VRH 2.7) Carlos Varela RPI March 19, 2012 Adapted with permission from:

More information

Lambda Calculus. Lecture 4 CS /26/10

Lambda Calculus. Lecture 4 CS /26/10 Lambda Calculus Lecture 4 CS 565 10/26/10 Pure (Untyped) Lambda Calculus The only value is a function Variables denote functions Functions always take functions as arguments Functions always return functions

More information

Functional Programming Languages (FPL)

Functional Programming Languages (FPL) Functional Programming Languages (FPL) 1. Definitions... 2 2. Applications... 2 3. Examples... 3 4. FPL Characteristics:... 3 5. Lambda calculus (LC)... 4 6. Functions in FPLs... 7 7. Modern functional

More information

Type Systems Winter Semester 2006

Type Systems Winter Semester 2006 Type Systems Winter Semester 2006 Week 4 November 8 November 15, 2006 - version 1.1 The Lambda Calculus The lambda-calculus If our previous language of arithmetic expressions was the simplest nontrivial

More information

Introduction to the Lambda Calculus

Introduction to the Lambda Calculus Introduction to the Lambda Calculus Overview: What is Computability? Church s Thesis The Lambda Calculus Scope and lexical address The Church-Rosser Property Recursion References: Daniel P. Friedman et

More information

Functional Programming

Functional Programming Functional Programming Overview! Functional vs. imperative programming! Fundamental concepts! Evaluation strategies! Pattern matching! Higher order functions! Lazy lists References! Richard Bird, Introduction

More information

CSCI-GA Scripting Languages

CSCI-GA Scripting Languages CSCI-GA.3033.003 Scripting Languages 12/02/2013 OCaml 1 Acknowledgement The material on these slides is based on notes provided by Dexter Kozen. 2 About OCaml A functional programming language All computation

More information

Constraint-based Analysis. Harry Xu CS 253/INF 212 Spring 2013

Constraint-based Analysis. Harry Xu CS 253/INF 212 Spring 2013 Constraint-based Analysis Harry Xu CS 253/INF 212 Spring 2013 Acknowledgements Many slides in this file were taken from Prof. Crista Lope s slides on functional programming as well as slides provided by

More information

Programming with Math and Logic

Programming with Math and Logic .. Programming with Math and Logic an invitation to functional programming Ed Morehouse Wesleyan University The Plan why fp? terms types interfaces The What and Why of Functional Programming Computing

More information

Lecture 4: Higher Order Functions

Lecture 4: Higher Order Functions Lecture 4: Higher Order Functions Søren Haagerup Department of Mathematics and Computer Science University of Southern Denmark, Odense September 26, 2017 HIGHER ORDER FUNCTIONS The order of a function

More information

1 Scope, Bound and Free Occurrences, Closed Terms

1 Scope, Bound and Free Occurrences, Closed Terms CS 6110 S18 Lecture 2 The λ-calculus Last time we introduced the λ-calculus, a mathematical system for studying the interaction of functional abstraction and functional application. We discussed the syntax

More information

Last class. CS Principles of Programming Languages. Introduction. Outline

Last class. CS Principles of Programming Languages. Introduction. Outline Last class CS6848 - Principles of Programming Languages Principles of Programming Languages V. Krishna Nandivada IIT Madras Interpreters A Environment B Cells C Closures D Recursive environments E Interpreting

More information

CSE 3302 Programming Languages Lecture 8: Functional Programming

CSE 3302 Programming Languages Lecture 8: Functional Programming CSE 3302 Programming Languages Lecture 8: Functional Programming (based on the slides by Tim Sheard) Leonidas Fegaras University of Texas at Arlington CSE 3302 L8 Spring 2011 1 Functional Programming Languages

More information

Lambda Calculus. CS 550 Programming Languages Jeremy Johnson

Lambda Calculus. CS 550 Programming Languages Jeremy Johnson Lambda Calculus CS 550 Programming Languages Jeremy Johnson 1 Lambda Calculus The semantics of a pure functional programming language can be mathematically described by a substitution process that mimics

More information

Functional Programming

Functional Programming Functional Programming COMS W4115 Prof. Stephen A. Edwards Spring 2003 Columbia University Department of Computer Science Original version by Prof. Simon Parsons Functional vs. Imperative Imperative programming

More information

CITS3211 FUNCTIONAL PROGRAMMING

CITS3211 FUNCTIONAL PROGRAMMING CITS3211 FUNCTIONAL PROGRAMMING 9. The λ calculus Summary: This lecture introduces the λ calculus. The λ calculus is the theoretical model underlying the semantics and implementation of functional programming

More information

INF 212 ANALYSIS OF PROG. LANGS LAMBDA CALCULUS. Instructors: Crista Lopes Copyright Instructors.

INF 212 ANALYSIS OF PROG. LANGS LAMBDA CALCULUS. Instructors: Crista Lopes Copyright Instructors. INF 212 ANALYSIS OF PROG. LANGS LAMBDA CALCULUS Instructors: Crista Lopes Copyright Instructors. History Formal mathematical system Simplest programming language Intended for studying functions, recursion

More information

Lecture 5: Lazy Evaluation and Infinite Data Structures

Lecture 5: Lazy Evaluation and Infinite Data Structures Lecture 5: Lazy Evaluation and Infinite Data Structures Søren Haagerup Department of Mathematics and Computer Science University of Southern Denmark, Odense October 3, 2017 How does Haskell evaluate a

More information

Functions as data. Massimo Merro. 9 November Massimo Merro The Lambda language 1 / 21

Functions as data. Massimo Merro. 9 November Massimo Merro The Lambda language 1 / 21 Functions as data Massimo Merro 9 November 2011 Massimo Merro The Lambda language 1 / 21 The core of sequential programming languages In the mid 1960s, Peter Landin observed that a complex programming

More information

COSE212: Programming Languages. Lecture 3 Functional Programming in OCaml

COSE212: Programming Languages. Lecture 3 Functional Programming in OCaml COSE212: Programming Languages Lecture 3 Functional Programming in OCaml Hakjoo Oh 2017 Fall Hakjoo Oh COSE212 2017 Fall, Lecture 3 September 18, 2017 1 / 44 Why learn ML? Learning ML is a good way of

More information

CS 457/557: Functional Languages

CS 457/557: Functional Languages CS 457/557: Functional Languages Lists and Algebraic Datatypes Mark P Jones Portland State University 1 Why Lists? Lists are a heavily used data structure in many functional programs Special syntax is

More information

CS 242. Fundamentals. Reading: See last slide

CS 242. Fundamentals. Reading: See last slide CS 242 Fundamentals Reading: See last slide Syntax and Semantics of Programs Syntax The symbols used to write a program Semantics The actions that occur when a program is executed Programming language

More information

CMSC 330: Organization of Programming Languages. Operational Semantics

CMSC 330: Organization of Programming Languages. Operational Semantics CMSC 330: Organization of Programming Languages Operational Semantics Notes about Project 4, Parts 1 & 2 Still due today (7/2) Will not be graded until 7/11 (along with Part 3) You are strongly encouraged

More information

The University of Nottingham SCHOOL OF COMPUTER SCIENCE A LEVEL 4 MODULE, SPRING SEMESTER MATHEMATICAL FOUNDATIONS OF PROGRAMMING ANSWERS

The University of Nottingham SCHOOL OF COMPUTER SCIENCE A LEVEL 4 MODULE, SPRING SEMESTER MATHEMATICAL FOUNDATIONS OF PROGRAMMING ANSWERS The University of Nottingham SCHOOL OF COMPUTER SCIENCE A LEVEL 4 MODULE, SPRING SEMESTER 2012 2013 MATHEMATICAL FOUNDATIONS OF PROGRAMMING ANSWERS Time allowed TWO hours Candidates may complete the front

More information

Introductory Example

Introductory Example CSc 520 Principles of Programming Languages 21: Lambda Calculus Introduction Christian Collberg Department of Computer Science University of Arizona collberg@cs.arizona.edu Copyright c 2005 Christian Collberg

More information

3. Functional Programming. Oscar Nierstrasz

3. Functional Programming. Oscar Nierstrasz 3. Functional Programming Oscar Nierstrasz Roadmap > Functional vs. Imperative Programming > Pattern Matching > Referential Transparency > Lazy Evaluation > Recursion > Higher Order and Curried Functions

More information

Shell CSCE 314 TAMU. Haskell Functions

Shell CSCE 314 TAMU. Haskell Functions 1 CSCE 314: Programming Languages Dr. Dylan Shell Haskell Functions 2 Outline Defining Functions List Comprehensions Recursion 3 Conditional Expressions As in most programming languages, functions can

More information

The Untyped Lambda Calculus

The Untyped Lambda Calculus Resources: The slides of this lecture were derived from [Järvi], with permission of the original author, by copy & x = 1 let x = 1 in... paste or by selection, annotation, or rewording. [Järvi] is in turn

More information

Simply-Typed Lambda Calculus

Simply-Typed Lambda Calculus #1 Simply-Typed Lambda Calculus #2 Back to School What is operational semantics? When would you use contextual (small-step) semantics? What is denotational semantics? What is axiomatic semantics? What

More information

The Untyped Lambda Calculus

The Untyped Lambda Calculus Resources: The slides of this lecture were derived from [Järvi], with permission of the original author, by copy & x = 1 let x = 1 in... paste or by selection, annotation, or rewording. [Järvi] is in turn

More information

Com S 541. Programming Languages I

Com S 541. Programming Languages I Programming Languages I Lecturer: TA: Markus Lumpe Department of Computer Science 113 Atanasoff Hall http://www.cs.iastate.edu/~lumpe/coms541.html TR 12:40-2, W 5 Pramod Bhanu Rama Rao Office hours: TR

More information

CSE 505: Concepts of Programming Languages

CSE 505: Concepts of Programming Languages CSE 505: Concepts of Programming Languages Dan Grossman Fall 2003 Lecture 6 Lambda Calculus Dan Grossman CSE505 Fall 2003, Lecture 6 1 Where we are Done: Modeling mutation and local control-flow Proving

More information

CMSC330 Spring 2017 Midterm 2

CMSC330 Spring 2017 Midterm 2 CMSC330 Spring 2017 Midterm 2 Name (PRINT YOUR NAME as it appears on gradescope ): Discussion Time (circle one) 10am 11am 12pm 1pm 2pm 3pm Discussion TA (circle one) Aaron Alex Austin Ayman Daniel Eric

More information

Haskell: From Basic to Advanced. Part 2 Type Classes, Laziness, IO, Modules

Haskell: From Basic to Advanced. Part 2 Type Classes, Laziness, IO, Modules Haskell: From Basic to Advanced Part 2 Type Classes, Laziness, IO, Modules Qualified types In the types schemes we have seen, the type variables were universally quantified, e.g. ++ :: [a] -> [a] -> [a]

More information

Programming Languages

Programming Languages Programming Languages Lambda Calculus and Scheme CSCI-GA.2110-003 Fall 2011 λ-calculus invented by Alonzo Church in 1932 as a model of computation basis for functional languages (e.g., Lisp, Scheme, ML,

More information

Advanced Topics in Programming Languages Lecture 2 - Introduction to Haskell

Advanced Topics in Programming Languages Lecture 2 - Introduction to Haskell Advanced Topics in Programming Languages Lecture 2 - Introduction to Haskell Ori Bar El Maxim Finkel 01/11/17 1 History Haskell is a lazy, committee designed, pure functional programming language that

More information

Introduction to Lambda Calculus. Lecture 7 CS /08/09

Introduction to Lambda Calculus. Lecture 7 CS /08/09 Introduction to Lambda Calculus Lecture 7 CS 565 02/08/09 Lambda Calculus So far, we ve explored some simple but non-interesting languages language of arithmetic expressions IMP (arithmetic + while loops)

More information

Background Type Classes (1B) Young Won Lim 6/28/18

Background Type Classes (1B) Young Won Lim 6/28/18 Background Type Classes (1B) Copyright (c) 2016-2017 Young W. Lim. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2

More information

Programming Languages, Summary CSC419; Odelia Schwartz

Programming Languages, Summary CSC419; Odelia Schwartz Programming Languages, Summary CSC419; Odelia Schwartz Chapter 1 Topics Reasons for Studying Concepts of Programming Languages Programming Domains Language Evaluation Criteria Influences on Language Design

More information

CMSC 330: Organization of Programming Languages. Lambda Calculus Encodings

CMSC 330: Organization of Programming Languages. Lambda Calculus Encodings CMSC 330: Organization of Programming Languages Lambda Calculus Encodings CMSC330 Spring 2018 1 The Power of Lambdas Despite its simplicity, the lambda calculus is quite expressive: it is Turing complete!

More information

Some Advanced ML Features

Some Advanced ML Features Some Advanced ML Features Mooly Sagiv Michael Clarkson, Cornell CS 3110 Data Structures and Functional Programming University of Washington: Dan Grossman ML is small Small number of powerful constructs

More information

Lambda Calculus. Type Systems, Lectures 3. Jevgeni Kabanov Tartu,

Lambda Calculus. Type Systems, Lectures 3. Jevgeni Kabanov Tartu, Lambda Calculus Type Systems, Lectures 3 Jevgeni Kabanov Tartu, 13.02.2006 PREVIOUSLY ON TYPE SYSTEMS Arithmetical expressions and Booleans Evaluation semantics Normal forms & Values Getting stuck Safety

More information

CPS 506 Comparative Programming Languages. Programming Language Paradigm

CPS 506 Comparative Programming Languages. Programming Language Paradigm CPS 506 Comparative Programming Languages Functional Programming Language Paradigm Topics Introduction Mathematical Functions Fundamentals of Functional Programming Languages The First Functional Programming

More information

JVM ByteCode Interpreter

JVM ByteCode Interpreter JVM ByteCode Interpreter written in Haskell (In under 1000 Lines of Code) By Louis Jenkins Presentation Schedule ( 15 Minutes) Discuss and Run the Virtual Machine first

More information

11/6/17. Outline. FP Foundations, Scheme. Imperative Languages. Functional Programming. Mathematical Foundations. Mathematical Foundations

11/6/17. Outline. FP Foundations, Scheme. Imperative Languages. Functional Programming. Mathematical Foundations. Mathematical Foundations Outline FP Foundations, Scheme In Text: Chapter 15 Mathematical foundations Functional programming λ-calculus LISP Scheme 2 Imperative Languages We have been discussing imperative languages C/C++, Java,

More information

Haskell Overview II (2A) Young Won Lim 9/26/16

Haskell Overview II (2A) Young Won Lim 9/26/16 (2A) Copyright (c) 2016 Young W. Lim. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version published

More information

A Quick Overview. CAS 701 Class Presentation 18 November Department of Computing & Software McMaster University. Church s Lambda Calculus

A Quick Overview. CAS 701 Class Presentation 18 November Department of Computing & Software McMaster University. Church s Lambda Calculus A Quick Overview CAS 701 Class Presentation 18 November 2008 Lambda Department of Computing & Software McMaster University 1.1 Outline 1 2 3 Lambda 4 5 6 7 Type Problem Lambda 1.2 Lambda calculus is a

More information

Chapter 15. Functional Programming Languages

Chapter 15. Functional Programming Languages Chapter 15 Functional Programming Languages Copyright 2009 Addison-Wesley. All rights reserved. 1-2 Chapter 15 Topics Introduction Mathematical Functions Fundamentals of Functional Programming Languages

More information

Functional Programming. Functional Programming

Functional Programming. Functional Programming 2014-06-27 Functional Programming Functional Programming 2014-06-27 Functional Programming 1 Imperative versus Functional Languages attributes of imperative languages: variables, destructive assignment,

More information

INTRODUCTION TO HASKELL

INTRODUCTION TO HASKELL INTRODUCTION TO HASKELL PRINCIPLES OF PROGRAMMING LANGUAGES Norbert Zeh Winter 2018 Dalhousie University 1/81 HASKELL: A PURELY FUNCTIONAL PROGRAMMING LANGUAGE Functions are first-class values: Can be

More information

CMSC 330: Organization of Programming Languages

CMSC 330: Organization of Programming Languages CMSC 330: Organization of Programming Languages Lambda Calculus Encodings CMSC 330 Summer 2017 1 The Power of Lambdas Despite its simplicity, the lambda calculus is quite expressive: it is Turing complete!

More information

Scala : an LLVM-targeted Scala compiler

Scala : an LLVM-targeted Scala compiler Scala : an LLVM-targeted Scala compiler Da Liu, UNI: dl2997 Contents 1 Background 1 2 Introduction 1 3 Project Design 1 4 Language Prototype Features 2 4.1 Language Features........................................

More information

CSCC24 Functional Programming Scheme Part 2

CSCC24 Functional Programming Scheme Part 2 CSCC24 Functional Programming Scheme Part 2 Carolyn MacLeod 1 winter 2012 1 Based on slides from Anya Tafliovich, and with many thanks to Gerald Penn and Prabhakar Ragde. 1 The Spirit of Lisp-like Languages

More information

Introduction to Lambda Calculus. Lecture 5 CS 565 1/24/08

Introduction to Lambda Calculus. Lecture 5 CS 565 1/24/08 Introduction to Lambda Calculus Lecture 5 CS 565 1/24/08 Lambda Calculus So far, we ve explored some simple but non-interesting languages language of arithmetic expressions IMP (arithmetic + while loops)

More information

Standard prelude. Appendix A. A.1 Classes

Standard prelude. Appendix A. A.1 Classes Appendix A Standard prelude In this appendix we present some of the most commonly used definitions from the standard prelude. For clarity, a number of the definitions have been simplified or modified from

More information

CS 6110 S14 Lecture 1 Introduction 24 January 2014

CS 6110 S14 Lecture 1 Introduction 24 January 2014 CS 6110 S14 Lecture 1 Introduction 24 January 2014 1 Introduction What is a program? Is it just something that tells the computer what to do? Yes, but there is much more to it than that. The basic expressions

More information

More Lambda Calculus and Intro to Type Systems

More Lambda Calculus and Intro to Type Systems More Lambda Calculus and Intro to Type Systems Plan Heavy Class Participation Thus, wake up! Lambda Calculus How is it related to real life? Encodings Fixed points Type Systems Overview Static, Dyamic

More information

Haske k ll An introduction to Functional functional programming using Haskell Purely Lazy Example: QuickSort in Java Example: QuickSort in Haskell

Haske k ll An introduction to Functional functional programming using Haskell Purely Lazy Example: QuickSort in Java Example: QuickSort in Haskell Haskell An introduction to functional programming using Haskell Anders Møller amoeller@cs.au.dk The most popular purely functional, lazy programming language Functional programming language : a program

More information