Principles of Programming Languages

Size: px
Start display at page:

Download "Principles of Programming Languages"

Transcription

1 Principles of Programming Languages Slides by Dana Fisman based on book by Mira Balaban and lecuture notes by Michael Elhadad Lesson 15 Type Inference Collaboration and Management Dana Fisman 1

2 Review of Last Lecture Scheme L4 define L1 only primitive ops and types L2 L3 cond lambda cons car cdr '() list letrec L5 Example of a fully typed expr: (define [g : [number * number -> number]] (lambda ([x : number] [y : number]) : number (+ x y))

3 Type checker { b:boolean, x:number, f:[empty -> T2], g:t2 } Fully typed expression E, type environment TEnv Type Checker ((lambda ([y : Ty] Type of E Applying non-proc / Wrong # of args / Wrong type of args / Non-boolean test

4 Type Checking System Typing Axioms o o For Literals (Booleans, Numbers) For Primitive Operators (+,-,*,/,<,>,=,not) Typing Inference Rules o o o o For Procedures For Applications For If

5 Type Checking Alg. Overview The alg. is a typical syntax-driven traversal of the expression AST. All the nodes in the AST are exhaustively traversed. On each node, we apply a typing rule and compute a type value. We maintain an environment reflecting the scope of variables o When a new scope is created (in procedure expressions), we extend the environment with the type of the declared parameters. o When variables are bound (e.g. in application expressions, let or letrec expressions) we check they adhere to the declared type

6 Type Checker vs. Interpreter Type Checker Interpreter Static Analysis: sees only program text Binds identifiers to types Compresses set of values (even of size) into types Always terminates Parses the body of an expr exactly once Dynamic Analysis: runs over actual data Binds identifiers to values (or locations) Treats elements of a certain type distinctly Might not terminate Parses the body of an expr zero to times

7

8 Type Inference More ambitious than type checking Type annotations may be missing (or nonexisting at all) Type inference algorithm needs not only to determine the expression type and that it is safe, but to infer the missing type annotations. The algorithm will rely on the operation of unification

9 Type Checking vs. Type Inference Type Checking Type Inference Fully Typed Expression e, Type Environment Tenv Partially Annotated Expression e Type Checker Type Inference Type of e wrt. Tenv Type- Error #... A typing Statement Tenv ` e : t Type- Error #...

10 Type Inference using Type Equations We will present an algorithm extending the type checker with type equations Type equations will be constructed for every sub-expression The type checking/inference procedure turns into a type equation solver

11 Type Inference Plan for today: o o o first learn to infer types manually then devise the algorithm First of all, lets recall the heart of type inference system: the axioms and inference rules

12 Recalling the Axioms and Inference Rules Typing axiom for atomic literals: Typing axiom Number: For every type environment _Tenv and number _n: _Tenv ` (num_exp _n) : Number Typing axiom Boolean : For every type environment _Tenv and boolean _b: _Tenv ` (bool_exp _b) : Boolean

13 Recalling the Axioms and Inference Rules Typing axiom for primitive ops: Typing axiom for +: For every type environment _Tenv: _Tenv ` + : [Number * * Number -> Number ] Typing axiom for <: For every type environment _Tenv: _Tenv ` < : [Number * Number -> Boolean] Typing axiom for not: For every type environment _Tenv and type expressions _S: _Tenv ` not: [_S -> Boolean]

14 Recalling the Axioms and Inference Rules Typing inference rule for Procedure: (lambda exp.) For every type environment _Tenv, variables _x1,..., _xn, n >= 0 expressions _e1,..., _em, m >= 1, and type expressions _S1,...,_Sn, _U1,...,_Um : Procedure with parameters (n > 0): If _Tenv o {_x1:_s1,..., _xn:_sn } ` _ei:_ui for all i = 1..m, Then _Tenv ` (lambda (_x1... _xn ) _e1... _em) : [_S1 *... * _Sn -> _Um] Parameter-less Procedure (n = 0): If _Tenv ` _ei:_ui for all i = 1..m, Then _Tenv `(lambda () _e1... _em) : [Empty -> _Um]

15 Recalling the Axioms and Inference Rules Typing inference rule for If: For every type environment _Tenv, expressions _test, _then, _else type expressions _S If _Tenv ` _test: Boolean _Tenv ` _then: _S _Tenv ` _else: _S Then _Tenv ` (if _test _then _else) : _S

16 Recalling the Axioms and Inference Rules Typing inference rule for Application: For every: type environment _Tenv, expressions _f, _e1,..., _en, n 0, and type expressions _S1,..., _Sn, _S: Procedure with parameters (n > 0): If _Tenv ` _f:[_s1*...*_sn -> _S], _Tenv ` _e1:_s1,... _Tenv ` _en:_sn Then _Tenv ` (_f _e1... _en):_s Parameter-less Procedure (n = 0): If _Tenv ` _f:[empty -> _S] Then _Tenv ` (_f):_s

17 Axioms and Inference Rules Typing inference rule for let: For every: type environment _Tenv, variables _x1,..., _xn, n >= 0 expressions _e1,..., _en, n 0, and expressions _b1,..., _bn, m 0, and type expressions _S1,..., _Sn, _U1,,_Um: Procedure with parameters (n > 0): If _Tenv {_x1 : _S1,..., _xn : _Sn } ` _bi : _Ui for all i = 1..n _Tenv ` _ei:_si for all i = 1..m Then _Tenv (let ([_x1 _e1]... [_xn _en]) _b1... _bm) : _Um

18 Axioms and Inference Rules Monotonicity Typing inference rule For every: type environments _Tenv, _Tenv expressions _e, n 0, and type expressions _S: If _Tenv ` _e :_S, Then _Tenv _Tenv ` _e :_S

19 Type Inference Ex. 1 Consider ((lambda (x) (+ x 3)) 5) With type annotations: ((lambda ( [x : Tx]) : T1 (+ x 3)) 5) We want to infer Tx and T1

20 Type Inference Ex. 1 ((lambda ([x : Tx]) : T1 (+ x 3)) 5) Tapp ((lambda (x) (+ x 3)) 5) Tproc (lambda (x) (+ x 3)) 5 Tn5 (+ x 3) T1 T+ + x 3 Tx Tn3

21 Type Inference Ex. 1 Tproc T+ [Num * Num -> Num] ((lambda (x) (+ x 3)) 5) (lambda (x) (+ x 3)) 5 (+ x 3) T1 + x 3 Tx Tapp Tn3 Number Tn5 Number Tproc = [Tx -> T1] T+ = [Tx * Tn3 -> T1] Tproc = [Tn5 -> Tapp] T+= [Num*Num->Num] Tx = Num T1 = Num Tproc = [Num->Num] Tapp = Num

22 Type Inference Ex. 1b Tapp ((lambda (x) (+ x 3)) 5) Tproc T+ [Num * Num -> Num] (lambda (x) (+ x 3)) (+ x 3) T1 + x 3 Tx Tn3 Number 'five Tfive Symbol Tproc = [Tx -> T1] T+ = [Tx * Tn3 -> T1] Tproc = [Tfive -> Tapp] T+= [Num*Num->Num] Tx = Num T1 = Num Tproc = [Num->Num] Tfive = Num

23 Type Inference Ex. 1c Tproc (lambda (x) (+ x 3)) We do not know what the type of x is and whether it is a Number (+ x 3) T1 Still, type inference will terminate fine. T+ [Num * Num -> Num] + x 3 Tx Tn3 Number but the inference alg. will return that Tproc : [Number -> Number] in an env. where x is assigned a Number

24 Type Inference Ex. 2 Consider (let ([x 1]) (lambda (f y) (f (+ x y)))) With type annotations: (let ([[x : Tx]) 1]) (lambda ([f : Tf] [y : Ty]) : Tres (f (+ x y)))) We want to infer Tx, Tf, Ty and Tres

25 Type Inference Ex. 2 Tlet (let ([x 1]) (lambda (f y) (f (+ x y)))) Tx x 1 Tn1 (lambda (f y) (f (+ x y))) Tproc (f (+ x y)) Tres f Tf (+ x y) Tplus (let ([x : Tx]) 1]) (lambda ([f : Tf]) [y : Ty]) : Tres (f (+ x y)))) + x y T+ Tx Ty

26 Type Inference Ex. 2 Tproc = [Tf * Ty -> Tres] T+= [Tx * Ty -> Tplus] T+= [Num * Num -> Num] Tx = Num Ty = Num Tplus = Num Tf = [Tplus -> Tres] Tf = [Tnum -> Tres] x 1 Tn1 Tproc = [[Tnum -> Tres] *Tnum] -> Tres Tlet = Tproc Tx Tlet = [[Tnum -> Tres] *Tnum] -> Tres (let ([x 1]) (lambda (f y) (f (+ x y)))) (lambda (f y) (f (+ x y))) f Tf (f (+ x y)) T+ Tlet (+ x y) + x y Tx Tproc Tres Tplus Ty

27 Type Inference Ex. 2 (let ([[x : Tx] 1]) (lambda ([f : Tf] [y : Ty]) : Tres (f (+ x y)))) We inferred Tx = Number, Ty = Number, Tf = [Number -> Tres], Tlet = [[Number -> Tres] * Number] -> Tres

28 Type Inference Ex. 3 Consider (lambda (x) (x x)) With type annotations: (lambda ([x : Tx]) : T1 (x x)) Tproc (lambda (x) (x x)) (x x) T1 We want to infer Tx and T1 x Tx x Tx

29 Type Inference Ex. 3 Tproc = [Tx -> T1] Tx = [Tx -> T1] Tproc (lambda (x) (x x)) T1 (x x) x Tx x Tx

30 Type Inference Algorithm using Type Equations The Alg. we present preforms type inference by solving type equations. Type equation solvers use the unification algorithm for unifying type expressions and producing consistent substitution of type variables which makes all equations equal.

31 Type Inference Algorithm using Type Equations The method has 4 stages: 1. Rename bound variables in given expression e. 2. Assign type variables to all sub-expressions of e. 3. Construct type equations. 4. Solve the equations. To define it formally we need to develop formal definitions for type-substitution and unifiers.

32 Type Substitution A type substitution s o is a mapping from a finite set of type variables to a finite set of type expressions s : TypeVars -> TypeExpr o such that s(t) does not refer to T. Substitutions are written using set notations o s : {T1=Boolean, T2=[Number->Boolean]} o s' :{T1=Number, T2=[[Number->T3]->T3]} o s" :{T1=Number, T2=[[Number->T3]->T2]}

33 Substitution Application Given a type expression T and a substitution s, the notation T s (or just Ts) denotes the application of s to T. The application T s consistently and simultaneously replaces all occurrences of type variables Ti in T by their mapped type expressions s(ti). E.g. [[T1->T2]->T2] {T1=Boolean, T2=[T3->T3]} = [[Boolean->[T3->T3]] -> [T3->T3]]

34 Type Instance / More General We say that a type expression T' is an instance of a type expression T, if there is a type substitution s such that T s = T'. T is more general than T', if T' is an instance of T. The following type expressions are instances of [T -> T]: o [Number -> Number] = [T->T] o {T = Number} o [Symbol -> Symbol] = [T->T] {T = Symbol} o [[Number->Number] -> [Number->Number]] = [T->T] {T = [Number->Number]} o [[Number->T1] -> [Number->T1]] = [T->T] {T = [Number->T1]}

35 Composition of Type Substitution The composition of type-substitutions s1 and s2, denoted s1 s2, is an operation that either results in a type-substitution, or fails. Intuitively, it adds the information on type variables in s2 to the information we already have in s1. Formally, it is defined as follows: 1. If type variable T is defined in both s1 and s2 then if there is a contradiction between s2(t) and s1(t) then composition fails, otherwise, if s2(t) is an instance of s1(t) then T is removed from s1 else it is removed from s2. 2. s2 is applied to the RHS of the type-expressions of s1 3. The (possibly modified) s2 is added to the (possibly modified) s1 4. Identity bindings, i.e., s2(t) = T, are removed. 5. If for some variable, (s1 s2)(t) refers to T, the composition fails.

36 Composition of Type Substitution For example, {T1=Number, T2=[[Number->T3] -> T3]} {T3=Boolean} = {T1=Number, T2 = [[Number->Boolean]->Boolean], T3 = Boolean} {T1=[T->T], T2=[[Number->T3] -> T1]} {T3=Boolean, T1=[Number->Number]} = {T1 = [Number->Number], T2 = [[Number->Boolean]->[Number->Number]], T3 = Boolean} {T1=[T->T], T2=[[Number->T3] -> T1]} {T3=Boolean, T1=Boolean} = fails

37 Renaming Renaming is the operation of consistent renaming of type variables within a type expression, by new type symbols, that do not occur in the type expression. Renamed type expressions are equivalent: o [[T1 -> T2]*T1 -> T2] [[S1 -> T2] * S1 -> T2] o [[T1 -> T2]*T1 -> T2] [[S1 -> S2] * S1 -> S2] o [[T1 -> T2]*T1 -> T2] [[T1 -> T2] * S2 -> T2] The variables in the substituting expressions should be new. o [[T1 -> T2]*T1 -> T2] [[T2 -> T2] * T2 -> T2] o [[T1 -> T2]*T1 -> T2] [[[T1->T2] -> T2] * [T1->T2] -> T2]

38 Unification & Unifier Defs. Unification is an operation that makes type expressions identical by application of the same type substitution to both expressions. When such a substitution can be found it is called a unifier of the two expressions. Let Te1 = [S * [Number -> S] -> S] Te2 = [Pair(T1) * T2 -> T3] Can you find a substitution that will unify them? Yes! TeU = {S=Pair(T1), T2=[Number->S], T3=Pair(T1)} is a unifier for Te1 & Te2. Proof: Te1 o TeU = [Pair(T1) * [Number->Pair(T1)] -> Pair(T1)] Te2 o TeU = [Pair(T1) * [Number->Pair(T1)] -> Pair(T1)]

39 Unification Ex. Let Te3 = [S * [Number -> S1] -> S] Te4 = [Pair(T1) * [T1 -> T1] -> T2] o Te3 & Te4 are unifiable by TeU = {S=Pair(Number), T2=Pair(Number), T1=Number, S1 = Number} Let Te5 = [S * [Number -> S] -> S] Te6 = [Pair(T1) * [T1 -> T1] -> T2] o Te5 & Te6 are not unifiable because we need to resolve the equalities S = Pair(T1) S = T2 [Number -> S] = [T1 -> T1] hence S = T1 which is not compatible with T1 = Pair(T1)

40 Most General Unifier (MGU) Unifiable type expressions can be unified by multiple unifiers. For example, Te7 = [S * S -> S] and Te8 = [Pair(T1) * T2 -> T2] are unifiable by the unifiers: TeU1 = {S=Pair(T1), T2=Pair(T1)} TeU2 = {S=Pair(Number), T2=Pair(Number)} TeU3 = {S=Pair(Boolean), T2=Pair(Boolean)} etc. Which is more general than the others? The unifier TeU1 is the most general unifier since it substitutes only the necessary type variables, without making additional assumptions about the replaced terms. All other unifiers are obtained from it by application of additional substitutions.

41 Most General Unifier (MGU) The most general unifier is unique, up to consistent renaming. It is called the most general unifier (mgu) of the two type expressions. The function unify(te1, TE2) returns o the mgu of TE1 and TE2 if it can be found and o false otherwise (indicating that TE1 and TE2 cannot be unified). We will use this function in our algorithm.

42 Type Inference w. Equations Step by Step Let s run the type inference algorithm step by step, on the following expression: (lambda (f g) (lambda (x) (f (+ x (g 3))))) First, let s consider it with type annotations: (lambda ([f : Tf] [g : Tg]) : T1 (lambda ([x : Tx]) : T2 (f (+ x (g 3)))))

43 Stage 1 : Renaming Not needed in this example, because all declared variables already have distinct names

44 Stage 2: Assign Type Variables Expression Variable (lambda (f g) (lambda (x) (f (+ x (g 3))))) T0 (lambda (x) (f (+ x (g 3)))) T1 (f (+ x (g 3))) T2 f Tf (+ x (g 3)) T3 + T+ x Tx (g 3) T4 g Tg 3 Tnum3

45 Stage 2: Assign Type Variables Expression Variable (lambda (f g) (lambda (x) (f (+ x (g 3))))) T0 (lambda (x) (f (+ x (g 3)))) T1 (f (+ x (g 3))) T2 f Tf (+ x (g 3)) T3 + T+ x Tx (g 3) T4 g Tg 3 Tnum3 (lambda (f g) (lambda (x) (f (+ x (g 3))))) T0 T1 T2 T3 T4

46 Stage 3: Construct type Equations We construct type equations involving the type variables we have defined. The type equations are constructed according to the corresponding typing axioms or typing inference rules. We thus start with equations for the atoms. o In our example, this adds two equations: Eq1: Tnum3 = Number Eq2: T+ = [Number * Number -> Number] (lambda (f g) (lambda (x) (f (+ x (g 3))))) T0 T1 T2 T3 T4

47 Stage 3: Construct type Equations What equations do procedure definitions create? For expression E = (lambda (v1...vn) e1... em) with n > 0, construct the equation: T E = [T v1 *... * T vn -> T em ]. For expression E = (lambda ( ) e1... em) construct the equation: T E = [Empty -> T em ].

48 Stage 3: Construct type Equations In our example we will create 2 equations following the inference rule for procedure definition: For E0 = (lambda (f g) (lambda (x) (f (+ x (g 3))))) we create Eq3: T0 = [Tf * Tg -> T1] For E1 = (lambda (x) (f (+ x (g 3)))) we create Eq4: T1 = [Tx -> T2] (lambda (f g) (lambda (x) (f (+ x (g 3))))) T0 T1 T2 T3 T4

49 Stage 3: Construct type Equations What equations do procedure applications create? For expression ae = (f e1... en) with n > 0, construct the equation: T f = [T e1 *... * T en -> T ae ]. For expression E = (f) construct the equation: T f = [Empty -> T ae ].

50 Stage 3: Construct type Equations In our example we will create 3 equations following the inference rule for procedure application: For E2 = (f (+ x (g 3))) we create Eq5: Tf = [T3-> T2] For E3 = (+ x (g 3)) we create Eq5: T+ = [Tx * T4 -> T3] For E4 = (g 3) we create Eq6: Tg = [Tnum3 -> T4] (lambda (f g) (lambda (x) (f (+ x (g 3))))) T0 T1 T2 T3 T4

51 Stage 3: Construct type Equations Equation Expression Tnum3 = Number 3 T+ = Number * Number -> Number + T0 = [Tf * Tg -> T1] E0 T1 = [Tx -> T2] E1 Tf = [T3 -> T2] E2 T+ = [Tx * T4 -> T3] E3 Tg = [Tnum3-> T4] E4 (lambda (f g) (lambda (x) (f (+ x (g 3))))) T0 T1 T2 T3 T4

52 Stage 4 : Solve the Equations Idea: The equations are solved by gradually producing typesubstitutions for all type variables. The solution is processed by considering the equations one by one. For an expression e, the algorithm infers a type t if the final type-substitution maps its variable Te to t. If an expression e has an inferred type then all of its sub-expressions have an inferred type as well. Circular type-substitution causes failure. If the procedure outputs FAIL then either there is a type error or the constructed type equations are too weak.

53 Alg. for Solving Equations Input: Equations - a set of type equations Output: A type substitution or FAIL Initialization: substitution := {} Repeat for each equation [te1 = te2] in Equations : 1. Apply the current substitution to the equation (replace vars by their substituting expressions). te1 = te1 substitution te2 = te2 substitution equation := [ te1 = te2 ] 2. Both sides of the eq. te1 and te2 are atomic types? If te1 te2 output FAIL. Else, do nothing. 3. One side of the eq. te1 or te2 is a variable? Say, te1 = T. Apply the substitution to the equation: equation = [ T = te2 ] Add the equation to the substitution: substitution := substitution {T = te2 } 4. A circular substitution occurred? Output FAIL. 5. Both side are composite with the same type constructor? Split into equations between corresponding components and add to the set of Equations Return substitution

54 Stage 4 : Solve the Equations Let s apply the algorithm to the set of equations we got from Stage 3 Equations Repeat Return 1. Apply 2. Both atomic types? 3. One a variable? 4. Circular? 5. Both composite of same type? T0 = [Tf * Tg -> T1] T1 = [Tx -> T2] Tf = [T3 -> T2] T+ = [Tx * T4 -> T3] Tg = [Tnum3-> T4] Tnum3 = Number T+ = Number * Number -> Number

55 Stage 4 : Solve the Equations Equations Substitution 1: T0 = [Tf * Tg -> T1] {} 2: T1 = [Tx -> T2] 3: Tf = [T3 -> T2] 4: T+ = [Tx * T4 -> T3] 5: Tg = [Tnum3-> T4] 6: Tnum3 = Number 7: T+ = Number * Number -> Number Equations Substitution 2: T1 = [Tx -> T2] {T0 = [Tf * Tg -> T1]} 3: Tf = [T3 -> T2] 4: T+ = [Tx * T4 -> T3] 5: Tg = [Tnum3-> T4] 6: Tnum3 = Number 7: T+ = Number * Number -> Number

56 Stage 4 : Solve the Equations Equations Substitution 2: T1 = [Tx -> T2] {T0 = [Tf*Tg -> T1]} 3: Tf = [T3 -> T2] 4: T+ = [Tx * T4 -> T3] 5: Tg = [Tnum3-> T4] 6: Tnum3 = Number 7: T+ = Number * Number -> Number Equations Substitution 3: Tf = [T3 -> T2] {T0 = [Tf*Tg -> [Tx->T2]], 4: T+ = [Tx * T4 -> T3] T1 = [Tx -> T2] } 5: Tg = [Tnum3-> T4] 6: Tnum3 = Number 7: T+ = Number * Number -> Number

57 Stage 4 : Solve the Equations Equations Substitution 3: Tf = [T3 -> T2] {T0 = [Tf * Tg -> [Tx->T2]], 4: T+ = [Tx * T4 -> T3] T1 = [Tx -> T2] } 5: Tg = [Tnum3-> T4] 6: Tnum3 = Number 7: T+ = Number * Number -> Number Equations Substitution 4: T+ = [Tx * T4 -> T3] {T0 = [[T3->T2] * Tg -> [Tx->T2]], 5: Tg = [Tnum3-> T4] T1 = [Tx -> T2], 6: Tnum3 = Number Tf = [T3 -> T2]} 7: T+ = Number * Number -> Number

58 Stage 4 : Solve the Equations Equations Substitution 4: T+ = [Tx * T4 -> T3] {T0 = [[T3->T2] * Tg -> [Tx->T2]], 5: Tg = [Tnum3-> T4] T1 = [Tx -> T2], 6: Tnum3 = Number Tf = [T3 -> T2]} 7: T+ = Number * Number -> Number Equations Substitution 5: Tg = [Tnum3-> T4] {T0 = [[T3->T2] * Tg -> [Tx->T2]], 6: Tnum3 = Number T1 = [Tx -> T2], 7: T+ = Number * Number -> Number Tf = [T3 -> T2], T+ = [Tx * T4 -> T3]}

59 Stage 4 : Solve the Equations Equations Substitution 5: Tg = [Tnum3 -> T4] {T0 = [[T3->T2] * Tg -> [Tx->T2]], 6: Tnum3 = Number T1 = [Tx -> T2], 7: T+ = Number * Number -> Number Tf = [T3 -> T2], T+ = [Tx * T4 -> T3]} Equations Substitution 6: Tnum3 = Number {T0 = [[T3->T2]*[Tnum3->T4]->[Tx->T2]], 7: T+ = Number * Number -> Number T1 = [Tx -> T2], Tf = [T3 -> T2], T+ = [Tx * T4 -> T3], Tg = [Tnum3-> T4]}

60 Stage 4 : Solve the Equations Equations Substitution 6: Tnum3 = Number {T0 = [[T3->T2]*[Tnum3->T4]->[Tx->T2]], 7: T+ = Number * Number -> Number T1 = [Tx -> T2], Tf = [T3 -> T2], T+ = [Tx * T4 -> T3], Tg = [Tnum3-> T4]} Equations Substitution 7: T+ = Number * Number -> Number {T0 = [[T3->T2]*[Number->T4]->[Tx->T2]], T1 = [Tx -> T2], Tf = [T3 -> T2], T+ = [Tx * T4 -> T3], Tg = [Number -> T4], Tnum3 = Number}

61 Stage 4 : Solve the Equations Equations Substitution 7: T+ = Number * Number -> Number {T0 = [[T3->T2]*[Number->T4]->[Tx->T2]], T1 = [Tx -> T2], Tf = [T3 -> T2], 7: Tx * T4 -> T3 = Number * Number -> Number T+ = [Tx * T4 -> T3], Tg = [Number -> T4], Tnum3 = Number} Equations Substitution 8: Tx = Number {T0 = [[T3->T2]*[Number->T4]->[Tx->T2]], 9: T4 = Number T1 = [Tx -> T2], 10: T3 = Number Tf = [T3 -> T2], T+ = [Tx * T4 -> T3], Tg = [Number -> T4], Tnum3 = Number}

62 Stage 4 : Solve the Equations Equations Substitution 8: Tx = Number {T0 = [[T3->T2]*[Number->T4]->[Tx->T2]], 9: T4 = Number T1 = [Tx -> T2], 10: T3 = Number Tf = [T3 -> T2], T+ = [Tx * T4 -> T3], Tg = [Number -> T4], Tnum3 = Number} Equations Substitution {T0 = [[Number ->T2]*[Number-> Number]->[Number ->T2]], T1 = [Number -> T2], Tf = [Number -> T2], T+ = [Number * Number -> Number], Tg = [Number -> Number], Tnum3 = Number, Tx = Number, T4 = Number, T3 = Number}

63 Completing the Ex. {T0 = [[Number ->T2]*[Number-> Number]->[Number ->T2]], T1 = [Number -> T2], Tf = [Number -> T2], T+ = [Number * Number -> Number], Tg = [Number -> Number], Tnum3 = Number, Tx = Number, T4 = Number, T3 = Number} Recall that we started with the following expression (lambda ([f : Tf] [g : Tg]) : T1 (lambda ([x : Tx]) : T2 (f (+ x (g 3))))) We can now use the resulting substitution to fully annotate it (lambda ([f : [Number -> T2]] [g : [Number -> Number]]) : [Number -> T2] (lambda ([x : Number]) : T2 (f (+ x (g 3)))))

Principles of Programming Languages

Principles of Programming Languages Principles of Programming Languages Lesson 14 Type Checking Collaboration and Management Dana Fisman www.cs.bgu.ac.il/~ppl172 1 Type Checking We return to the issue of type safety we discussed informally,

More information

עקרונות שפות תכנות, סמסטר ב' 2016 תרגול 7: הסקת טיפוסים סטטית. Axiomatic Type Inference

עקרונות שפות תכנות, סמסטר ב' 2016 תרגול 7: הסקת טיפוסים סטטית. Axiomatic Type Inference עקרונות שפות תכנות, סמסטר ב' 2016 תרגול 7: הסקת טיפוסים סטטית 1. Axiomatic type inference 2. Type inference using type constraints נושאי התרגול: Axiomatic Type Inference Definition (seen in class): A Type-substitution

More information

Principles of Programming Languages

Principles of Programming Languages Principles of Programming Languages www.cs.bgu.ac.il/~ppl172 Lesson 6 - Defining a Programming Language Bottom Up Collaboration and Management - Elements of Programming Dana Fisman 1 What we accomplished

More information

Comp 311: Sample Midterm Examination

Comp 311: Sample Midterm Examination Comp 311: Sample Midterm Examination October 29, 2007 Name: Id #: Instructions 1. The examination is closed book. If you forget the name for a Scheme operation, make up a name for it and write a brief

More information

Type Declarations. Γ <num> : num [... <id> τ... ] <id> : τ Γ true : bool Γ false : bool Γ e 1 : num Γ e 2 : num Γ. {+ e 1 e 2 } : num

Type Declarations. Γ <num> : num [... <id> τ... ] <id> : τ Γ true : bool Γ false : bool Γ e 1 : num Γ e 2 : num Γ. {+ e 1 e 2 } : num Type Declarations Γ : num [... τ... ] : τ Γ true : bool Γ false : bool Γ e 1 : num Γ e 2 : num Γ {+ e 1 e 2 } : num Γ e 1 : bool Γ e 2 : τ 0 Γ e 3 : τ 0 Γ {if e 1 e 2 e 3 } : τ 0 Γ[

More information

עקרונות שפות תכנות 2018 תרגול 8 Type Inference System

עקרונות שפות תכנות 2018 תרגול 8 Type Inference System עקרונות שפות תכנות 2018 תרגול 8 Type Inference System Type Inference System The Type Inference System is a TypeScript Implementation of the algorithm for Type Checking and Inference using Type Equations.

More information

Functional Programming. Pure Functional Programming

Functional Programming. Pure Functional Programming Functional Programming Pure Functional Programming Computation is largely performed by applying functions to values. The value of an expression depends only on the values of its sub-expressions (if any).

More information

Type Soundness. Type soundness is a theorem of the form If e : τ, then running e never produces an error

Type Soundness. Type soundness is a theorem of the form If e : τ, then running e never produces an error Type Soundness Type soundness is a theorem of the form If e : τ, then running e never produces an error 1 Type Soundness Type soundness is a theorem of the form If e : τ, then running e never produces

More information

LECTURE 16. Functional Programming

LECTURE 16. Functional Programming LECTURE 16 Functional Programming WHAT IS FUNCTIONAL PROGRAMMING? Functional programming defines the outputs of a program as a mathematical function of the inputs. Functional programming is a declarative

More information

Module 6. Knowledge Representation and Logic (First Order Logic) Version 2 CSE IIT, Kharagpur

Module 6. Knowledge Representation and Logic (First Order Logic) Version 2 CSE IIT, Kharagpur Module 6 Knowledge Representation and Logic (First Order Logic) 6.1 Instructional Objective Students should understand the advantages of first order logic as a knowledge representation language Students

More information

CS 314 Principles of Programming Languages

CS 314 Principles of Programming Languages CS 314 Principles of Programming Languages Lecture 17: Functional Programming Zheng (Eddy Zhang Rutgers University April 4, 2018 Class Information Homework 6 will be posted later today. All test cases

More information

Scheme in Scheme: The Metacircular Evaluator Eval and Apply

Scheme in Scheme: The Metacircular Evaluator Eval and Apply Scheme in Scheme: The Metacircular Evaluator Eval and Apply CS21b: Structure and Interpretation of Computer Programs Brandeis University Spring Term, 2015 The metacircular evaluator is A rendition of Scheme,

More information

Announcements. The current topic: Scheme. Review: BST functions. Review: Representing trees in Scheme. Reminder: Lab 2 is due on Monday at 10:30 am.

Announcements. The current topic: Scheme. Review: BST functions. Review: Representing trees in Scheme. Reminder: Lab 2 is due on Monday at 10:30 am. The current topic: Scheme! Introduction! Object-oriented programming: Python Functional programming: Scheme! Introduction! Numeric operators, REPL, quotes, functions, conditionals! Function examples, helper

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

6.037 Lecture 4. Interpretation. What is an interpreter? Why do we need an interpreter? Stages of an interpreter. Role of each part of the interpreter

6.037 Lecture 4. Interpretation. What is an interpreter? Why do we need an interpreter? Stages of an interpreter. Role of each part of the interpreter 6.037 Lecture 4 Interpretation Interpretation Parts of an interpreter Meta-circular Evaluator (Scheme-in-scheme!) A slight variation: dynamic scoping Original material by Eric Grimson Tweaked by Zev Benjamin,

More information

CMSC 330: Organization of Programming Languages

CMSC 330: Organization of Programming Languages CMSC 330: Organization of Programming Languages Operational Semantics CMSC 330 Summer 2018 1 Formal Semantics of a Prog. Lang. Mathematical description of the meaning of programs written in that language

More information

Variables. Substitution

Variables. Substitution Variables Elements of Programming Languages Lecture 4: Variables, binding and substitution James Cheney University of Edinburgh October 6, 2015 A variable is a symbol that can stand for another expression.

More information

User-defined Functions. Conditional Expressions in Scheme

User-defined Functions. Conditional Expressions in Scheme User-defined Functions The list (lambda (args (body s to a function with (args as its argument list and (body as the function body. No quotes are needed for (args or (body. (lambda (x (+ x 1 s to the increment

More information

Type Declarations. [... <id> τ... ] <id> : τ. Γ <num> : number. Γ true : boolean. Γ false : boolean. Γ e 1 : number.

Type Declarations. [... <id> τ... ] <id> : τ. Γ <num> : number. Γ true : boolean. Γ false : boolean. Γ e 1 : number. Type Inference 1 Type Declarations Γ : number Γ true : boolean Γ e 1 : number [... τ... ] : τ Γ false : boolean Γ e 2 : number Γ {+ e 1 e 2 } : number Γ e 1 : boolean Γ e 2 : τ 0 Γ e 3

More information

Fall Semester, The Metacircular Evaluator. Today we shift perspective from that of a user of computer langugaes to that of a designer of

Fall Semester, The Metacircular Evaluator. Today we shift perspective from that of a user of computer langugaes to that of a designer of 1 MASSACHVSETTS INSTITVTE OF TECHNOLOGY Department of Electrical Engineering and Computer Science 6.001 Structure and Interpretation of Computer Programs Fall Semester, 1996 Lecture Notes { October 31,

More information

6.184 Lecture 4. Interpretation. Tweaked by Ben Vandiver Compiled by Mike Phillips Original material by Eric Grimson

6.184 Lecture 4. Interpretation. Tweaked by Ben Vandiver Compiled by Mike Phillips Original material by Eric Grimson 6.184 Lecture 4 Interpretation Tweaked by Ben Vandiver Compiled by Mike Phillips Original material by Eric Grimson 1 Interpretation Parts of an interpreter Arithmetic calculator

More information

Typed Scheme: Scheme with Static Types

Typed Scheme: Scheme with Static Types Typed Scheme: Scheme with Static Types Version 4.1.1 Sam Tobin-Hochstadt October 5, 2008 Typed Scheme is a Scheme-like language, with a type system that supports common Scheme programming idioms. Explicit

More information

CS 314 Principles of Programming Languages

CS 314 Principles of Programming Languages CS 314 Principles of Programming Languages Lecture 16: Functional Programming Zheng (Eddy Zhang Rutgers University April 2, 2018 Review: Computation Paradigms Functional: Composition of operations on data.

More information

1. For every evaluation of a variable var, the variable is bound.

1. For every evaluation of a variable var, the variable is bound. 7 Types We ve seen how we can use interpreters to model the run-time behavior of programs. Now we d like to use the same technology to analyze or predict the behavior of programs without running them.

More information

6.821 Programming Languages Handout Fall MASSACHVSETTS INSTITVTE OF TECHNOLOGY Department of Electrical Engineering and Compvter Science

6.821 Programming Languages Handout Fall MASSACHVSETTS INSTITVTE OF TECHNOLOGY Department of Electrical Engineering and Compvter Science 6.821 Programming Languages Handout Fall 2002 MASSACHVSETTS INSTITVTE OF TECHNOLOGY Department of Electrical Engineering and Compvter Science Problem Set 6 Problem 1: cellof Subtyping Do exercise 11.6

More information

;;; Determines if e is a primitive by looking it up in the primitive environment. ;;; Define indentation and output routines for the output for

;;; Determines if e is a primitive by looking it up in the primitive environment. ;;; Define indentation and output routines for the output for Page 1/11 (require (lib "trace")) Allow tracing to be turned on and off (define tracing #f) Define a string to hold the error messages created during syntax checking (define error msg ""); Used for fancy

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

CS558 Programming Languages

CS558 Programming Languages CS558 Programming Languages Winter 2017 Lecture 7b Andrew Tolmach Portland State University 1994-2017 Values and Types We divide the universe of values according to types A type is a set of values and

More information

Computer Science 21b (Spring Term, 2015) Structure and Interpretation of Computer Programs. Lexical addressing

Computer Science 21b (Spring Term, 2015) Structure and Interpretation of Computer Programs. Lexical addressing Computer Science 21b (Spring Term, 2015) Structure and Interpretation of Computer Programs Lexical addressing The difference between a interpreter and a compiler is really two points on a spectrum of possible

More information

Introduction to Scheme

Introduction to Scheme How do you describe them Introduction to Scheme Gul Agha CS 421 Fall 2006 A language is described by specifying its syntax and semantics Syntax: The rules for writing programs. We will use Context Free

More information

Principles of Programming Languages, Spring 2016 Assignment 5 Logic Programming

Principles of Programming Languages, Spring 2016 Assignment 5 Logic Programming Principles of Programming Languages, Spring 2016 Assignment 5 Logic Programming Submission instructions: a. Submit an archive file named id1_id2.zip where id1 and id2 are the IDs of the students responsible

More information

Principles of Programming Languages

Principles of Programming Languages Principles f Prgramming Languages Slides by Dana Fisman based n bk by Mira Balaban and lecuture ntes by Michael Elhadad Dana Fisman Lessn 16 Type Inference System www.cs.bgu.ac.il/~ppl172 1 Type Inference

More information

Lecture #13: Type Inference and Unification. Typing In the Language ML. Type Inference. Doing Type Inference

Lecture #13: Type Inference and Unification. Typing In the Language ML. Type Inference. Doing Type Inference Lecture #13: Type Inference and Unification Typing In the Language ML Examples from the language ML: fun map f [] = [] map f (a :: y) = (f a) :: (map f y) fun reduce f init [] = init reduce f init (a ::

More information

Typed Racket: Racket with Static Types

Typed Racket: Racket with Static Types Typed Racket: Racket with Static Types Version 5.0.2 Sam Tobin-Hochstadt November 6, 2010 Typed Racket is a family of languages, each of which enforce that programs written in the language obey a type

More information

A Brief Introduction to Scheme (II)

A Brief Introduction to Scheme (II) A Brief Introduction to Scheme (II) Philip W. L. Fong pwlfong@cs.uregina.ca Department of Computer Science University of Regina Regina, Saskatchewan, Canada Lists Scheme II p.1/29 Lists Aggregate data

More information

CS 314 Principles of Programming Languages

CS 314 Principles of Programming Languages CS 314 Principles of Programming Languages Lecture 18: Functional Programming Zheng (Eddy) Zhang Rutgers University April 9, 2018 Review: Defining Scheme Functions (define ( lambda (

More information

Mid-Term 2 Grades

Mid-Term 2 Grades Mid-Term 2 Grades 100 46 1 HW 9 Homework 9, in untyped class interpreter: Add instanceof Restrict field access to local class Implement overloading (based on argument count) Due date is the same as for

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

Project 2: Scheme Interpreter

Project 2: Scheme Interpreter Project 2: Scheme Interpreter CSC 4101, Fall 2017 Due: 12 November 2017 For this project, you will implement a simple Scheme interpreter in C++ or Java. Your interpreter should be able to handle the same

More information

Programming Languages

Programming Languages Programming Languages Tevfik Koşar Lecture - XIII March 2 nd, 2006 1 Roadmap Functional Languages Lambda Calculus Intro to Scheme Basics Functions Bindings Equality Testing Searching 2 1 Functional Languages

More information

CS61A Midterm 2 Review (v1.1)

CS61A Midterm 2 Review (v1.1) Spring 2006 1 CS61A Midterm 2 Review (v1.1) Basic Info Your login: Your section number: Your TA s name: Midterm 2 is going to be held on Tuesday 7-9p, at 1 Pimentel. What will Scheme print? What will the

More information

Overloading, Type Classes, and Algebraic Datatypes

Overloading, Type Classes, and Algebraic Datatypes Overloading, Type Classes, and Algebraic Datatypes Delivered by Michael Pellauer Arvind Computer Science and Artificial Intelligence Laboratory M.I.T. September 28, 2006 September 28, 2006 http://www.csg.csail.mit.edu/6.827

More information

A Small Interpreted Language

A Small Interpreted Language A Small Interpreted Language What would you need to build a small computing language based on mathematical principles? The language should be simple, Turing equivalent (i.e.: it can compute anything that

More information

Comp 411 Principles of Programming Languages Lecture 7 Meta-interpreters. Corky Cartwright January 26, 2018

Comp 411 Principles of Programming Languages Lecture 7 Meta-interpreters. Corky Cartwright January 26, 2018 Comp 411 Principles of Programming Languages Lecture 7 Meta-interpreters Corky Cartwright January 26, 2018 Denotational Semantics The primary alternative to syntactic semantics is denotational semantics.

More information

Lecture 15 CIS 341: COMPILERS

Lecture 15 CIS 341: COMPILERS Lecture 15 CIS 341: COMPILERS Announcements HW4: OAT v. 1.0 Parsing & basic code generation Due: March 28 th No lecture on Thursday, March 22 Dr. Z will be away Zdancewic CIS 341: Compilers 2 Adding Integers

More information

6.001 Notes: Section 8.1

6.001 Notes: Section 8.1 6.001 Notes: Section 8.1 Slide 8.1.1 In this lecture we are going to introduce a new data type, specifically to deal with symbols. This may sound a bit odd, but if you step back, you may realize that everything

More information

Flang typechecker Due: February 27, 2015

Flang typechecker Due: February 27, 2015 CMSC 22610 Winter 2015 Implementation of Computer Languages I Flang typechecker Due: February 27, 2015 Project 3 February 9, 2015 1 Introduction The third project is to implement a type checker for Flang,

More information

Scheme: Data. CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Monday, April 3, Glenn G.

Scheme: Data. CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Monday, April 3, Glenn G. Scheme: Data CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Monday, April 3, 2017 Glenn G. Chappell Department of Computer Science University of Alaska Fairbanks ggchappell@alaska.edu

More information

Lecture 12: Conditional Expressions and Local Binding

Lecture 12: Conditional Expressions and Local Binding Lecture 12: Conditional Expressions and Local Binding Introduction Corresponds to EOPL 3.3-3.4 Please review Version-1 interpreter to make sure that you understand how it works Now we will extend the basic

More information

CSSE 304 Assignment #13 (interpreter milestone #1) Updated for Fall, 2018

CSSE 304 Assignment #13 (interpreter milestone #1) Updated for Fall, 2018 CSSE 304 Assignment #13 (interpreter milestone #1) Updated for Fall, 2018 Deliverables: Your code (submit to PLC server). A13 participation survey (on Moodle, by the day after the A13 due date). This is

More information

Functional Programming. Pure Functional Languages

Functional Programming. Pure Functional Languages Functional Programming Pure functional PLs S-expressions cons, car, cdr Defining functions read-eval-print loop of Lisp interpreter Examples of recursive functions Shallow, deep Equality testing 1 Pure

More information

Denotational Semantics. Domain Theory

Denotational Semantics. Domain Theory Denotational Semantics and Domain Theory 1 / 51 Outline Denotational Semantics Basic Domain Theory Introduction and history Primitive and lifted domains Sum and product domains Function domains Meaning

More information

Functional Programming. Pure Functional Languages

Functional Programming. Pure Functional Languages Functional Programming Pure functional PLs S-expressions cons, car, cdr Defining functions read-eval-print loop of Lisp interpreter Examples of recursive functions Shallow, deep Equality testing 1 Pure

More information

The Substitution Model

The Substitution Model The Substitution Model Prof. Clarkson Fall 2017 Today s music: Substitute by The Who Review Previously in 3110: simple interpreter for expression language abstract syntax tree (AST) evaluation based on

More information

Bindings & Substitution

Bindings & Substitution Bindings & Substitution Even in our simple language, we encounter repeated expressions. 1 {* {+ 4 2} {+ 4 2}} There are several reasons to eliminate duplicated code. It introduces a redundant computation.

More information

Organization of Programming Languages CS3200/5200N. Lecture 11

Organization of Programming Languages CS3200/5200N. Lecture 11 Organization of Programming Languages CS3200/5200N Razvan C. Bunescu School of Electrical Engineering and Computer Science bunescu@ohio.edu Functional vs. Imperative The design of the imperative languages

More information

Principles of Programming Languages

Principles of Programming Languages Principles of Programming Languages www.cs.bgu.ac.il/~ppl172 Lesson 4 - Type Checking Collaboration and Management Dana Fisman 1 Why declare types? Declaring types allows the compiler to detect errors

More information

Type Checking. Outline. General properties of type systems. Types in programming languages. Notation for type rules.

Type Checking. Outline. General properties of type systems. Types in programming languages. Notation for type rules. Outline Type Checking General properties of type systems Types in programming languages Notation for type rules Logical rules of inference Common type rules 2 Static Checking Refers to the compile-time

More information

CS61A Discussion Notes: Week 11: The Metacircular Evaluator By Greg Krimer, with slight modifications by Phoebus Chen (using notes from Todd Segal)

CS61A Discussion Notes: Week 11: The Metacircular Evaluator By Greg Krimer, with slight modifications by Phoebus Chen (using notes from Todd Segal) CS61A Discussion Notes: Week 11: The Metacircular Evaluator By Greg Krimer, with slight modifications by Phoebus Chen (using notes from Todd Segal) What is the Metacircular Evaluator? It is the best part

More information

Scheme: Strings Scheme: I/O

Scheme: Strings Scheme: I/O Scheme: Strings Scheme: I/O CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Wednesday, April 5, 2017 Glenn G. Chappell Department of Computer Science University of

More information

Outline. General properties of type systems. Types in programming languages. Notation for type rules. Common type rules. Logical rules of inference

Outline. General properties of type systems. Types in programming languages. Notation for type rules. Common type rules. Logical rules of inference Type Checking Outline General properties of type systems Types in programming languages Notation for type rules Logical rules of inference Common type rules 2 Static Checking Refers to the compile-time

More information

Lecture #23: Conversion and Type Inference

Lecture #23: Conversion and Type Inference Lecture #23: Conversion and Type Inference Administrivia. Due date for Project #2 moved to midnight tonight. Midterm mean 20, median 21 (my expectation: 17.5). Last modified: Fri Oct 20 10:46:40 2006 CS164:

More information

Why do we need an interpreter? SICP Interpretation part 1. Role of each part of the interpreter. 1. Arithmetic calculator.

Why do we need an interpreter? SICP Interpretation part 1. Role of each part of the interpreter. 1. Arithmetic calculator. .00 SICP Interpretation part Parts of an interpreter Arithmetic calculator Names Conditionals and if Store procedures in the environment Environment as explicit parameter Defining new procedures Why do

More information

Introduction to Typed Racket. The plan: Racket Crash Course Typed Racket and PL Racket Differences with the text Some PL Racket Examples

Introduction to Typed Racket. The plan: Racket Crash Course Typed Racket and PL Racket Differences with the text Some PL Racket Examples Introduction to Typed Racket The plan: Racket Crash Course Typed Racket and PL Racket Differences with the text Some PL Racket Examples Getting started Find a machine with DrRacket installed (e.g. the

More information

Fall 2018 Discussion 8: October 24, 2018 Solutions. 1 Introduction. 2 Primitives

Fall 2018 Discussion 8: October 24, 2018 Solutions. 1 Introduction. 2 Primitives CS 6A Scheme Fall 208 Discussion 8: October 24, 208 Solutions Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write

More information

Program Analysis: Lecture 02 Page 1 of 32

Program Analysis: Lecture 02 Page 1 of 32 Program Analysis: Lecture 02 Page 1 of 32 Program Analysis/ Mooly Sagiv Lecture 1, 31/10/2012 Operational Semantics Notes by: Kalev Alpernas As background to the subject of Program Analysis, we will first

More information

Polymorphic lambda calculus Princ. of Progr. Languages (and Extended ) The University of Birmingham. c Uday Reddy

Polymorphic lambda calculus Princ. of Progr. Languages (and Extended ) The University of Birmingham. c Uday Reddy 06-02552 Princ. of Progr. Languages (and Extended ) The University of Birmingham Spring Semester 2016-17 School of Computer Science c Uday Reddy2016-17 Handout 6: Polymorphic Type Systems 1. Polymorphic

More information

Functional Languages. Hwansoo Han

Functional Languages. Hwansoo Han Functional Languages Hwansoo Han Historical Origins Imperative and functional models Alan Turing, Alonzo Church, Stephen Kleene, Emil Post, etc. ~1930s Different formalizations of the notion of an algorithm

More information

Conversion vs. Subtyping. Lecture #23: Conversion and Type Inference. Integer Conversions. Conversions: Implicit vs. Explicit. Object x = "Hello";

Conversion vs. Subtyping. Lecture #23: Conversion and Type Inference. Integer Conversions. Conversions: Implicit vs. Explicit. Object x = Hello; Lecture #23: Conversion and Type Inference Administrivia. Due date for Project #2 moved to midnight tonight. Midterm mean 20, median 21 (my expectation: 17.5). In Java, this is legal: Object x = "Hello";

More information

Functional Programming - 2. Higher Order Functions

Functional Programming - 2. Higher Order Functions Functional Programming - 2 Higher Order Functions Map on a list Apply Reductions: foldr, foldl Lexical scoping with let s Functional-11, CS5314, Sp16 BGRyder 1 Higher Order Functions Functions as 1st class

More information

Building a system for symbolic differentiation

Building a system for symbolic differentiation Computer Science 21b Structure and Interpretation of Computer Programs Building a system for symbolic differentiation Selectors, constructors and predicates: (constant? e) Is e a constant? (variable? e)

More information

Chapter 15 Functional Programming Languages

Chapter 15 Functional Programming Languages Chapter 15 Functional Programming Languages Fundamentals of Functional Programming Languages Introduction to Scheme A programming paradigm treats computation as the evaluation of mathematical functions.

More information

Name EID. (calc (parse '{+ {with {x {+ 5 5}} {with {y {- x 3}} {+ y y} } } z } ) )

Name EID. (calc (parse '{+ {with {x {+ 5 5}} {with {y {- x 3}} {+ y y} } } z } ) ) CS 345 Spring 2010 Midterm Exam Name EID 1. [4 Points] Circle the binding instances in the following expression: (calc (parse '+ with x + 5 5 with y - x 3 + y y z ) ) 2. [7 Points] Using the following

More information

Lambda the Ultimate. Corky Cartwright Vivek Sarkar Department of Computer Science Rice University

Lambda the Ultimate. Corky Cartwright Vivek Sarkar Department of Computer Science Rice University Lambda the Ultimate Corky Cartwright Vivek Sarkar Department of Computer Science Rice University 1 Function filter2: variant of filter1 function from last lecture ;; filter2 : test lon -> lon ;; to construct

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

cs173: Programming Languages Final Exam

cs173: Programming Languages Final Exam cs173: Programming Languages Final Exam Fall 2002 Please read this page of instructions before you turn the page! This exam is worth 102 points. We will assign partial credit to partial responses, provided

More information

Lecture 09: Data Abstraction ++ Parsing is the process of translating a sequence of characters (a string) into an abstract syntax tree.

Lecture 09: Data Abstraction ++ Parsing is the process of translating a sequence of characters (a string) into an abstract syntax tree. Lecture 09: Data Abstraction ++ Parsing Parsing is the process of translating a sequence of characters (a string) into an abstract syntax tree. program text Parser AST Processor Compilers (and some interpreters)

More information

Principles of Programming Languages

Principles of Programming Languages Principles of Programming Languages Lesson Collaboration 22 An Introduction and Management to Logic Programming Dana Fisman Logic Programming ( Pure Prolog ) www.cs.bgu.ac.il/~ppl172 1 Review of Last Lecture

More information

Scheme Quick Reference

Scheme Quick Reference Scheme Quick Reference COSC 18 Fall 2003 This document is a quick reference guide to common features of the Scheme language. It is not intended to be a complete language reference, but it gives terse summaries

More information

CSE341: Programming Languages Lecture 17 Implementing Languages Including Closures. Dan Grossman Autumn 2018

CSE341: Programming Languages Lecture 17 Implementing Languages Including Closures. Dan Grossman Autumn 2018 CSE341: Programming Languages Lecture 17 Implementing Languages Including Closures Dan Grossman Autumn 2018 Typical workflow concrete syntax (string) "(fn x => x + x) 4" Parsing Possible errors / warnings

More information

Below are example solutions for each of the questions. These are not the only possible answers, but they are the most common ones.

Below are example solutions for each of the questions. These are not the only possible answers, but they are the most common ones. 6.001, Fall Semester, 2002 Quiz II Sample solutions 1 MASSACHVSETTS INSTITVTE OF TECHNOLOGY Department of Electrical Engineering and Computer Science 6.001 Structure and Interpretation of Computer Programs

More information

CS558 Programming Languages

CS558 Programming Languages CS558 Programming Languages Fall 2016 Lecture 7a Andrew Tolmach Portland State University 1994-2016 Values and Types We divide the universe of values according to types A type is a set of values and a

More information

Scheme Quick Reference

Scheme Quick Reference Scheme Quick Reference COSC 18 Winter 2003 February 10, 2003 1 Introduction This document is a quick reference guide to common features of the Scheme language. It is by no means intended to be a complete

More information

Programming Languages Third Edition

Programming Languages Third Edition Programming Languages Third Edition Chapter 12 Formal Semantics Objectives Become familiar with a sample small language for the purpose of semantic specification Understand operational semantics Understand

More information

Typed Recursion {with {mk-rec : (((num -> num) -> (num -> num)) -> (num -> num)) {fun {body : ((num -> num) -> (num -> num))} {{fun {fx :

Typed Recursion {with {mk-rec : (((num -> num) -> (num -> num)) -> (num -> num)) {fun {body : ((num -> num) -> (num -> num))} {{fun {fx : Recursion {with {mk-rec {fun {body} {{fun {fx} {fx fx}} {fun {fx} {{fun {f} {body f}} {fun {x} {{fx fx} x}}}}}}} {with {fib {mk-rec {fun {fib} {fun {n} {if0 n 1 {if0 {- n 1} 1 {+ {fib {- n 1}} {fib {-

More information

Normal Order (Lazy) Evaluation SICP. Applicative Order vs. Normal (Lazy) Order. Applicative vs. Normal? How can we implement lazy evaluation?

Normal Order (Lazy) Evaluation SICP. Applicative Order vs. Normal (Lazy) Order. Applicative vs. Normal? How can we implement lazy evaluation? Normal Order (Lazy) Evaluation Alternative models for computation: Normal (Lazy) Order Evaluation Memoization Streams Applicative Order: evaluate all arguments, then apply operator Normal Order: pass unevaluated

More information

CSE341 Autumn 2017, Final Examination December 12, 2017

CSE341 Autumn 2017, Final Examination December 12, 2017 CSE341 Autumn 2017, Final Examination December 12, 2017 Please do not turn the page until 2:30. Rules: The exam is closed-book, closed-note, etc. except for both sides of one 8.5x11in piece of paper. Please

More information

Software Paradigms (Lesson 4) Functional Programming Paradigm

Software Paradigms (Lesson 4) Functional Programming Paradigm Software Paradigms (Lesson 4) Functional Programming Paradigm Table of Contents 1 Introduction... 2 2 Evaluation of Functions... 3 3 Compositional (Construct) Operators... 4 4 Some Implementation Issues...

More information

Discussion 12 The MCE (solutions)

Discussion 12 The MCE (solutions) Discussion 12 The MCE (solutions) ;;;;METACIRCULAR EVALUATOR FROM CHAPTER 4 (SECTIONS 4.1.1-4.1.4) of ;;;; STRUCTURE AND INTERPRETATION OF COMPUTER PROGRAMS ;;;from section 4.1.4 -- must precede def of

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

Formal Systems and their Applications

Formal Systems and their Applications Formal Systems and their Applications Dave Clarke (Dave.Clarke@cs.kuleuven.be) Acknowledgment: these slides are based in part on slides from Benjamin Pierce and Frank Piessens 1 Course Overview Introduction

More information

FP Foundations, Scheme

FP Foundations, Scheme FP Foundations, Scheme In Text: Chapter 15 1 Functional Programming -- Prelude We have been discussing imperative languages C/C++, Java, Fortran, Pascal etc. are imperative languages Imperative languages

More information

SML A F unctional Functional Language Language Lecture 19

SML A F unctional Functional Language Language Lecture 19 SML A Functional Language Lecture 19 Introduction to SML SML is a functional programming language and acronym for Standard d Meta Language. SML has basic data objects as expressions, functions and list

More information

Higher-Order Logic. Specification and Verification with Higher-Order Logic

Higher-Order Logic. Specification and Verification with Higher-Order Logic Higher-Order Logic Specification and Verification with Higher-Order Logic Arnd Poetzsch-Heffter (Slides by Jens Brandt) Software Technology Group Fachbereich Informatik Technische Universität Kaiserslautern

More information

From Syntactic Sugar to the Syntactic Meth Lab:

From Syntactic Sugar to the Syntactic Meth Lab: From Syntactic Sugar to the Syntactic Meth Lab: Using Macros to Cook the Language You Want a V E N E TRUT H Brandeis S PA R T U N T O I T S I N N E R M OS T COMPUTER SCIENCE 21B: Structure and Interpretation

More information

Type Processing by Constraint Reasoning

Type Processing by Constraint Reasoning , Martin Sulzmann, Jeremy Wazny 8th November 2006 Chameleon Chameleon is Haskell-style language treats type problems using constraints gives expressive error messages has a programmable type system Developers:

More information

CS153: Compilers Lecture 14: Type Checking

CS153: Compilers Lecture 14: Type Checking CS153: Compilers Lecture 14: Type Checking Stephen Chong https://www.seas.harvard.edu/courses/cs153 Announcements Project 4 out Due Thursday Oct 25 (7 days) Project 5 out Due Tuesday Nov 13 (26 days) Project

More information

CSE 413 Languages & Implementation. Hal Perkins Winter 2019 Structs, Implementing Languages (credits: Dan Grossman, CSE 341)

CSE 413 Languages & Implementation. Hal Perkins Winter 2019 Structs, Implementing Languages (credits: Dan Grossman, CSE 341) CSE 413 Languages & Implementation Hal Perkins Winter 2019 Structs, Implementing Languages (credits: Dan Grossman, CSE 341) 1 Goals Representing programs as data Racket structs as a better way to represent

More information

Pierce Ch. 3, 8, 11, 15. Type Systems

Pierce Ch. 3, 8, 11, 15. Type Systems Pierce Ch. 3, 8, 11, 15 Type Systems Goals Define the simple language of expressions A small subset of Lisp, with minor modifications Define the type system of this language Mathematical definition using

More information

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define CS 6A Scheme Summer 207 Discussion 0: July 25, 207 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,

More information