# Begin at the beginning

Save this PDF as:

Size: px
Start display at page:

## Transcription

1 Begin at the beginning Expressions (Syntax) Exec-time Dynamic Values (Semantics) Compile-time Static Types 1. Programmer enters expression 2. ML checks if expression is well-typed Using a precise set of rules, ML tries to find a unique type for the expression meaningful type for the expr 3. ML evaluates expression to compute value Of the same type found in step 2

2 Tail Recursion: Factorial let rec fact n = if n<=0 then 1 else n * fact (n-1);; 2

3 How does it execute? let rec fact n = if n<=0 then 1 else n * fact (n-1);; fac 3;; 3

4 Tail recursion Tail recursion: recursion where all recursive calls are immediately followed by a return in other words: not allowed to do anything between recursive call and return 4

5 Tail recursive factorial let fact x = 5

6 Tail recursive factorial let fact x = let rec helper x curr = if x <= 0 then curr else helper (x - 1) (x * curr) in helper x 1;; 6

7 How does it execute? let fact x = let rec helper x curr = if x <= 0 then curr else helper (x - 1) (x * curr) in helper x 1;; fact 3;; 7

8 Tail recursion Tail recursion: for each recursive call, the value of the recursive call is immediately returned in other words: not allowed to do anything between recursive call and return Why do we care about tail recursion? it turns out that tail recursion can be optimized into a simple loop 8

9 Compiler can optimize! let fact x = let rec helper x curr = if x <= 0 fact(x) { curr := 1; while (1) { if (x <= 0) then curr then { return curr } else helper (x - 1) (x * curr) else { x := x 1; curr := (x * curr) } in } helper x 1;; recursion! Loop! 9

10 Tail recursion summary Tail recursive calls can be optimized as a jump Part of the language specification of some languages (ie: you can count on the compiler to optimize tail recursive calls) 10

11 Base Types

12 Base Type: int Expressions built from sub-expressions Types computed from types of sub-expressions Values computed from values of sub-expressions

13 Base Type: int 2; 2 i i:int i ) i 2+3; 5 e1 + e2 e 1 :int e 2 :int e 1 +e 2 :int e1)v1 e2)v2 e1+e2)v1+v2 7-4; 3 e1 - e2 e 1 :int e 2 :int e 1 -e 2 :int e1)v1 e2)v2 e1-e2)v1-v2 (2+3)*(7-4); 15 e1 * e2 e 1 :int e 2 :int e 1 * e 2 :int e1)v1 e2)v2 e1*e2)v1*v2 Expressions built from sub-expressions Types computed from types of sub-expressions Values computed from values of sub-expressions

14 Base Type: float e r:float r ) r e1 +. e2 e 1 :float e 1 :float e 1 +.e 2 :float e1)v1 e2)v2 e1+.e2)v1+.v e1 -. e2 e 1 :float e 2 :float e 1 -.e 2 :float e1)v1 e2)v2 e1-.e2)v1-.v2 ( ) /. ( ) e1 /. e2 e 1 :float e 2 :float e 1 /.e 2 :float e1)v1 e2)v2 e1/.e2)v1/.v2 Expressions built from sub-expressions Types computed from types of sub-expressions Values computed from values of sub-expressions

15 Base Type: string ab ab s s:string s ) s ab ^ cd abcd e1^e2 e 1 :string e 2 :string e 1^e 2 :string e1)v1 e2)v2 e1^e2)v1^v2 Expressions built from sub-expressions Types computed from types of sub-expressions Values computed from values of sub-expressions

16 Base Type: bool true true b b:bool b ) b 2 < 3 true e1 < e2 e 1 :int e 1 :int e 1 < e 2 :bool e1)v1 e2)v2 e1<e2 ) v1<v2 not(2<3) false not e e : bool not e : bool e ) v not e ) not v ( ab = cd ) false e1 = e2 e 1 :T e 2 :T e 1 =e 2 : bool e1)v1 e2)v2 e1=e2 ) v1=v2 not (2<3) && ( ab = cd ) false e1 && e2 e 1 :bool e 2 :bool e 1 &&e 2 :bool e1)v1 e2)v2 e1&&e2) v1 && v2

17 Base Type: bool Equality testing is built-in for all expr,values,types but compared expressions must have same type except for? function values why? ( ab = cd ) false e1 = e2 e 1 :T e 2 :T e 1 =e 2 : bool e1)v1 e2)v2 e1=e2 ) v1=v2

18 Type Errors pq ^ 9; (2 + a ); e 1 :string e 2 :string e 1^e 2 :string e 1 :int e 2 :int e 1 + e 2 : int Expressions built from sub-expressions Types computed from types of sub-expression If a sub-expression is not well-typed then whole expression is not well-typed 0 * (2 + a );

19 Complex types: Tuples (2+2, 7>8); (4,false) int * bool

20 Complex types: Tuples (2+2, 7>8); (4,false) int * bool e1:t1 e2:t2 (e 1,e 2 ) : T1 * T2 e1)v1 e2)v2 (e1,e2)) (v1,v2)

21 Complex types: Tuples Can be of any fixed size (9-3, ab ^ cd,7>8) (6, abcd, false) (int * string * bool) e1:t1 e2:t2 en: Tn (e1,e2,,en) : T1 * T2* * Tn e1)v1 e2)v2 en ) vn (e1,e2,,en)) (v1,v2,,vn) Elements can have different types Tuples can be nested in other tuples

22 Complex types: Records {name= sarah ; age=31; pass=false} { name : string, age : int, pass : bool} Records are tuples with named elements {name= sarah ;age=31;pass=false}.age 31 int {age=31;name= sarah ;pass=false}.age 31 int {age=31;name= sarah ;pass=false}.pass false bool

23 But wait All evaluation rules look like: e1)v1 e2)v2 e1 OP e2 ) v1 OP v2

24 Complex types: Lists [1+1;2+2;3+3;4+4] [2;4;6;8] int list [ a ; b ; c ^ d ]; [ a ; b ; cd ] string list [(1; a ^ b );(3+4, c )]; [(1, ab );(7, c )] (int*string) list [[1];[2;3];[4;5;6]]; [[1];[2;3];[4;5;6]]; (int list) list Unbounded size Can have lists of anything (e.g. lists of lists)

25 Complex types: Lists

26 Complex types: Lists [] []: a list [] ) [] [e1;e2;e3; ] e1:t e2: T e3: T [e1;e2;e3; ] : T list e1)v1 e2)v2 e3)v3 [e1;e2; ] ) [v1;v2; ] All elements have the same type [1; pq ]

27 Complex types: list..construct

28 Complex types: list..construct Cons operator 1::[2;3] [1;2;3] int list e1:t e2: T list e1::e2 : T list e1)v1 e2 ) v2 e1::e2 ) v1::v2 1::[ b ; cd ]; Can only cons element to a list of same type

29 Complex types: list construct Append operator [1;2;3;4] int list e1:t list e2: T list : T list e1)v1 e2 ) v2 ) b ; cd ]; b ; cd ]; Can only append lists of the same type

30 Complex types: list deconstruct Reading the elements of a list: Two operators : hd (head) and tl (tail) [1;2;3;4;5] hd [1;2;3;4;5] 1 int tl [1;2;3;4;5] [2;3;4;5] int list [ a ; b ; cd ] hd [ a ; b ; cd ] a tl [ a ; b ; cd ] [ b ; cd ] string string list [(1, a );(7, c )] hd [(1, a );(7, c )] (1, a ) Int * string tl [(1, a );(7, c )] [(7; c )] (int * string) list [[];[1;2;3];[4;5]] hd [[];[1;2;3];4;5] 1 tl [[];[1;2;3];4;5] [2;3;4;5] int list int list list

32 List: Heads and Tails Head e :T list hd e : T e )v1::v2 hd e ) v1 Tail e :T list tl e : T list e ) v1::v2 tl e ) v2 (hd [[];[1;2;3]]) = (hd [[];[ a ]]) int list e 1 :T e 2 :T e 1 =e 2 : bool string list

33 Recap Expressions (Syntax) Exec-time Dynamic Values (Semantics) Compile-time Static Types 1. Programmer enters expression 2. ML checks if expression is well-typed Using a precise set of rules, ML tries to find a unique type for the expression meaningful type for the expr 3. ML evaluates expression to compute value Of the same type found in step 2

34 Recap Integers: +,-,* floats: +,-,* Booleans: =,<, andalso, orelse, not Strings: ^ Tuples, Records: #i Fixed number of values, of different types Lists: Unbounded number of values, of same type

35 If-then-else expressions if (1 < 2) then 5 else 10 5 int if (1 < 2) then [ ab, cd ] else [ x ] [ ab, cd ] If-then-else is also an expression! Can use any expression in then, else branch if e1 then e2 else e3 string list

36 If-then-else expressions if (1 < 2) then 5 else 10 5 int if (1 < 2) then [ ab, cd ] else [ x ] [ ab, cd ] If-then-else is also an expression! Can use any expression in then, else branch if e1 then e2 else e3 string list e1 : bool e2: T e3: T if e1 then e2 else e3 : T e1 ) true e2 ) v2 if e1 then e2 else e3 ) v2 e1 ) false e3 ) v3 if e1 then e2 else e3 ) v3

37 If-then-else expressions if (1 < 2) then [1;2] else 5 if false then [1;2] else 5 then-subexp, else-subexp must have same type! which is the type of resulting expression e1 : bool e2: T e3: T if e1 then e2 else e3 : T

38 If-then-else expressions e1 : bool e2: T e3: T if e1 then e2 else e3 : T Then-subexp, Else-subexp must have same type! Equals type of resulting expression if 1>2 then [1,2] else [] [] int list if 1<2 then [] else [ a ] [] string list (if 1>2 then [1,2] else [])=(if 1<2 then [] else [ a ])

39 Next: Variables

40 Variables and Bindings Q: How to use variables in ML? Q: How to assign to a variable? # let x = 2+2;; val x : int = 4 let x = e;; Bind the value of expression e to the variable x

41 Variables and Bindings # let x = 2+2;; val x : int = 4 # let y = x * x * x;; val y : int = 64 # let z = [x;y;x+y];; val z : int list = [4;64;68] Later declared expressions can use x Most recent bound value used for evaluation Sounds like C/Java? NO!

42 Environments ( Phone Book ) How ML deals with variables Variables = names Values = phone number x y z x 4 : int 64 : int [4;64;68] : int list 8 : int

43 Environments and Evaluation ML begins in a top-level environment Some names bound let x = e;; ML program = Sequence of variable bindings Program evaluated by evaluating bindings in order 1. Evaluate expr e in current env to get value v : t 2. Extend env to bind x to v : t (Repeat with next binding)

44 Environments Phone book Variables = names Values = phone number 1. Evaluate: Find and use most recent value of variable 2. Extend: Add new binding at end of phone book

45 Example # let x = 2+2;; val x : int = 4 x 4 : int # let y = x * x * x;; val y : int = 64 # let z = [x;y;x+y];; val z : int list = [4;64;68] # let x = x + x ;; val x : int = 8 New binding! x y x y z x y z x 4 : int 64 : int 4 : int 64 : int [4;64;68] : int list 4 : int 64 : int [4;64;68] : int list 8 : int

46 Environments 1. Evaluate: Use most recent bound value of var 2. Extend: Add new binding at end How is this different from C/Java s store? # let x = 2+2;; val x : int = 4 x 4 : int # let f = fun y -> x + y; val f : int -> int = fn # let x = x + x ; val x : int = 8 # f 0; val it : int = 4 x 4 : int f fn <code, >: int->int New binding: No change or mutation Old binding frozen in f

47 Environments 1. Evaluate: Use most recent bound value of var 2. Extend: Add new binding at end How is this different from C/Java s store? # let x = 2+2;; val x : int = 4 x 4 : int # let f = fun y -> x + y; val f : int -> int = fn # let x = x + x ; val x : int = 8 # f 0; val it : int = 4 x 4 : int f fn <code, >: int->int x 4 : int f fn <code, >: int->int x 8 : int

48 Environments 1. Evaluate: Use most recent bound value of var 2. Extend: Add new binding at end How is this different from C/Java s store? # let x = 2+2;; val x : int = 4 # let f = fun y -> x + y; val f : int -> int = fn # let x = x + x ; val x : int = 8 # f 0; val it : int = 4 Binding used to eval (f ) x 4 : int f fn <code, >: int->int x 8 : int Binding for subsequent x

49 Cannot change the world Cannot assign to variables Can extend the env by adding a fresh binding Does not affect previous uses of variable Environment at fun declaration frozen inside fun value Frozen env used to evaluate application (f ) Q: Why is this a good thing? # let x = 2+2;; val x : int = 4 # let f = fun y -> x + y;; val f : int -> int = fn # let x = x + x ;; val x : int = 8; # f 0;; val it : int = 4 Binding used to eval (f ) x 4 : int f fn <code, >: int->int x 8 : int Binding for subsequent x

50 Cannot change the world Q: Why is this a good thing? A: Function behavior frozen at declaration Nothing entered afterwards affects function Same inputs always produce same outputs Localizes debugging Localizes reasoning about the program No sharing means no evil aliasing

51 Examples of no sharing Remember: No addresses, no sharing. Each variable is bound to a fresh instance of a value Tuples, Lists Efficient implementation without sharing? There is sharing and pointers but hidden from you Compiler s job is to optimize code Efficiently implement these no-sharing semantics Your job is to use the simplified semantics Write correct, cleaner, readable, extendable systems

52 Recap: Environments Phone book Variables = names Values = phone number 1. Evaluate: Find and use most recent value of variable 2. Extend: let x = e ;; Add new binding at end of phone book

53 Next: Functions Expressions Values Types

54 Functions expr Functions are values, can bind using let let fname = fun x -> e ;; Problem: Can t define recursive functions! fname is bound after computing rhs value no (or old ) binding for occurences of fname inside e let rec fname x = e ;; Occurences of fname inside e bound to this definition let rec fac x = if x<=1 then 1 else x*fac (x-1)

55 Functions Type

56 Functions Type e1 : T2 -> T e1 e2 : T e2: T2

57 Functions Values Two questions about function values: What is the value: 1. of a function? 2. of a function application (call)? (e1 e2)

58 Functions Values Two questions about function values: What is the value: 1. of a function? 2. of a function application (call)? (e1 e2)

59 Values of functions: Closures Body expression not evaluated until application but type-checking takes place at compile time i.e. when function is defined Function value = <code + environment at definition> closure # let x = 2+2;; val x : int = 4 # let f = fun y -> x + y;; val f : int -> int = fn # let x = x + x ;; val x : int = 8 # f 0;; val it : int = 4 Binding used to eval (f ) x 4 : int f fn <code, >: int->int x 8 : int Binding for subsequent x

60 Values of function application Application: fancy word for call (e1 e2) apply the argument e2 to the (function) e1 Application Value: 1. Evaluate e1 in current env to get (function) v1 v1 is code + env code is (formal x + body e), env is E 2. Evaluate e2 in current env to get (argument) v2 3. Evaluate body e in env E extended by binding x to v2

61 Example 1 let x = 1;; let f y = x + y;; let x = 2;; let y = 3;; f (x + y);;

62 Example 1 let x = 1;; let f y = x + y;; let x = 2;; let y = 3;; f (x + y);;

63 Example 2 let x = 1;; let f y = let x = 2 in fun z -> x + y + z ;; let x = 100;; let g =(f 4);; let y = 100;; (g 1);;

64 Example 2 let x = 1;; let f y = let x = 2 in fun z -> x + y + z ;; let x = 100;; let g = (f 4);; let y = 100;; (g 1);;

65 Example 3 let f g = let x = 0 in g 2 ;; let x = 100;; let h y = x + y;; f h;;

66 Static/Lexical Scoping For each occurrence of a variable, Unique place in program text where variable defined Most recent binding in environment Static/Lexical: Determined from the program text Without executing the programy Very useful for readability, debugging: Don t have to figure out where a variable got assigned Unique, statically known definition for each occurrence

67 Alternative: dynamic scoping let x = 100 let f y = x + y let g x = f 0 let z = g 0 (* value of z? *)

### Tail Recursion: Factorial. Begin at the beginning. How does it execute? Tail recursion. Tail recursive factorial. Tail recursive factorial

Begin at the beginning Epressions (Synta) Compile-time Static Eec-time Dynamic Types Values (Semantics) 1. Programmer enters epression 2. ML checks if epression is well-typed Using a precise set of rules,

### Programming Languages

CSE 130 : Spring 2011 Programming Languages Lecture 3: Crash Course Ctd, Expressions and Types Ranjit Jhala UC San Diego A shorthand for function binding # let neg = fun f -> fun x -> not (f x); # let

### Variables and Bindings

Net: Variables Variables and Bindings Q: How to use variables in ML? Q: How to assign to a variable? # let = 2+2;; val : int = 4 let = e;; Bind the value of epression e to the variable Variables and Bindings

### sum: tree -> int sum_leaf: tree -> int sum_leaf: tree -> int Representing Trees Next: Lets get cosy with Recursion Sum up the leaf values. E.g.

Representing Trees Node Next: Lets get cosy with Recursion 1 2 3 1 Node 2 3 Node(Node( 1, 2), 3) sum: tree -> int Next: Lets get cosy with Recursion Sum up the leaf values. E.g. # let t0 = sum Node(Node(

### Recap. Recap. If-then-else expressions. If-then-else expressions. If-then-else expressions. If-then-else expressions

Recap Epressions (Synta) Compile-time Static Eec-time Dynamic Types (Semantics) Recap Integers: +,-,* floats: +,-,* Booleans: =,

### News. Programming Languages. Recap. Recap: Environments. Functions. of functions: Closures. CSE 130 : Fall Lecture 5: Functions and Datatypes

CSE 130 : Fall 2007 Programming Languages News PA deadlines shifted PA #2 now due 10/24 (next Wed) Lecture 5: Functions and Datatypes Ranjit Jhala UC San Diego Recap: Environments Phone book Variables

### Programming Languages

CSE 130 : Winter 2009 Programming Languages News PA 2 out, and due Mon 1/26 5pm Lecture 5: Functions and Datatypes t UC San Diego Recap: Environments Phone book Variables = names Values = phone number

### Any questions. Say hello to OCaml. Say hello to OCaml. Why readability matters. History, Variants. Plan (next 4 weeks)

Any questions Say hello to OCaml? void sort(int arr[], int beg, int end){ if (end > beg + 1){ int piv = arr[beg]; int l = beg + 1; int r = end; while (l!= r-1){ if(arr[l]

### Recap from last time. Programming Languages. CSE 130 : Fall Lecture 3: Data Types. Put it together: a filter function

CSE 130 : Fall 2011 Recap from last time Programming Languages Lecture 3: Data Types Ranjit Jhala UC San Diego 1 2 A shorthand for function binding Put it together: a filter function # let neg = fun f

### So what does studying PL buy me?

So what does studying PL buy me? Enables you to better choose the right language but isn t that decided by libraries, standards, and my boss? Yes. Chicken-and-egg. My goal: educate tomorrow s tech leaders

### Recap: ML s Holy Trinity

Recap: ML s Holy Trinity Expressions (Syntax) Exec-time Dynamic Values (Semantics) Compile-time Static Types 1. Programmer enters expression 2. ML checks if expression is well-typed Using a precise set

### CSE 130 Programming Languages. Lecture 3: Datatypes. Ranjit Jhala UC San Diego

CSE 130 Programming Languages Lecture 3: Datatypes Ranjit Jhala UC San Diego News? PA #2 (coming tonight) Ocaml-top issues? Pleas post questions to Piazza Recap: ML s Holy Trinity Expressions (Syntax)

### A quick introduction to SML

A quick introduction to SML CMSC 15300 April 9, 2004 1 Introduction Standard ML (SML) is a functional language (or higherorder language) and we will use it in this course to illustrate some of the important

### Tuples. CMSC 330: Organization of Programming Languages. Examples With Tuples. Another Example

CMSC 330: Organization of Programming Languages OCaml 2 Higher Order Functions Tuples Constructed using (e1,..., en) Deconstructed using pattern matching Patterns involve parens and commas, e.g., (p1,p2,

### SCHEME 7. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. October 29, 2015

SCHEME 7 COMPUTER SCIENCE 61A October 29, 2015 1 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,

### Scope, Functions, and Storage Management

Scope, Functions, and Storage Management Implementing Functions and Blocks cs3723 1 Simplified Machine Model (Compare To List Abstract Machine) Registers Code Data Program Counter (current instruction)

### 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

### 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

### A Brief Introduction to Standard ML

A Brief Introduction to Standard ML Specification and Verification with Higher-Order Logic Arnd Poetzsch-Heffter (Slides by Jens Brandt) Software Technology Group Fachbereich Informatik Technische Universität

### CSC324- TUTORIAL 5. Shems Saleh* *Some slides inspired by/based on Afsaneh Fazly s slides

CSC324- TUTORIAL 5 ML Shems Saleh* *Some slides inspired by/based on Afsaneh Fazly s slides Assignment 1 2 More questions were added Questions regarding the assignment? Starting ML Who am I? Shems Saleh

### 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";

### # true;; - : bool = true. # false;; - : bool = false 9/10/ // = {s (5, "hi", 3.2), c 4, a 1, b 5} 9/10/2017 4

Booleans (aka Truth Values) Programming Languages and Compilers (CS 421) Sasa Misailovic 4110 SC, UIUC https://courses.engr.illinois.edu/cs421/fa2017/cs421a # true;; - : bool = true # false;; - : bool

### Patterns The Essence of Functional Programming

Patterns The Essence of Functional Programming Up to now we have defined functions in a very traditional way: function name + variable name parameters Read Chap 7 In functional programming we can exploit

### Functional programming Primer I

Functional programming Primer I COS 320 Compiling Techniques Princeton University Spring 2016 Lennart Beringer 1 Characteristics of functional programming Primary notions: functions and expressions (not

### Writing Evaluators MIF08. Laure Gonnord

Writing Evaluators MIF08 Laure Gonnord Laure.Gonnord@univ-lyon1.fr Evaluators, what for? Outline 1 Evaluators, what for? 2 Implementation Laure Gonnord (Lyon1/FST) Writing Evaluators 2 / 21 Evaluators,

### Control Structures. Lecture 4 COP 3014 Fall September 18, 2017

Control Structures Lecture 4 COP 3014 Fall 2017 September 18, 2017 Control Flow Control flow refers to the specification of the order in which the individual statements, instructions or function calls

### 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

### Lists. Michael P. Fourman. February 2, 2010

Lists Michael P. Fourman February 2, 2010 1 Introduction The list is a fundamental datatype in most functional languages. ML is no exception; list is a built-in ML type constructor. However, to introduce

### ;;; 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

### Which of the following expressions has the type int list?

Which of the following expressions has the type int list? 1) [3; true] 2) [1;2;3]::[1;2] 3) []::[1;2]::[] 4) (1::2)::(3::4)::[] 5) [1;2;3;4] Answer: 5 Which of the following expressions has the type (int

### Fall 2017 Discussion 7: October 25, 2017 Solutions. 1 Introduction. 2 Primitives

CS 6A Scheme Fall 207 Discussion 7: October 25, 207 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

### Scope and Introduction to Functional Languages. Review and Finish Scoping. Announcements. Assignment 3 due Thu at 11:55pm. Website has SML resources

Scope and Introduction to Functional Languages Prof. Evan Chang Meeting 7, CSCI 3155, Fall 2009 Announcements Assignment 3 due Thu at 11:55pm Submit in pairs Website has SML resources Text: Harper, Programming

### Scope. Chapter Ten Modern Programming Languages 1

Scope Chapter Ten Modern Programming Languages 1 Reusing Names Scope is trivial if you have a unique name for everything: fun square a = a * a; fun double b = b + b; But in modern languages, we often use

### Programming Languages

CSE 130 : Spring 2011 Programming Languages Lecture 13: What s in a Name? Ranjit Jhala UC San Diego Next: What s in a name? More precisely: How should programmer think of data What does a variable x really

### Next: What s in a name? Programming Languages. Data model in functional PL. What s in a name? CSE 130 : Fall Lecture 13: What s in a Name?

Next: What s in a name? CSE 13 : Fall 211 Programming Languages Lecture 13: What s in a Name? More precisely: How should programmer think of data What does a variable x really mean? Ranjit Jhala UC San

### Semantic Analysis. Outline. The role of semantic analysis in a compiler. Scope. Types. Where we are. The Compiler Front-End

Outline Semantic Analysis The role of semantic analysis in a compiler A laundry list of tasks Scope Static vs. Dynamic scoping Implementation: symbol tables Types Static analyses that detect type errors

### Programming Languages. So why study PL? A Programming Language. A different language is a different vision of life. CSE 130 : Fall 2012

CSE 130 : Fall 2012 Programming Languages Lecture 1: Hello, world. Ranjit Jhala UC San Diego 1 2 A Programming Language So why study PL? Two variables x, y Three operations x++ x-- (x=0)? L1:L2; L1: x++;

### Compilers Project 3: Semantic Analyzer

Compilers Project 3: Semantic Analyzer CSE 40243 Due April 11, 2006 Updated March 14, 2006 Overview Your compiler is halfway done. It now can both recognize individual elements of the language (scan) and

### CSci 4223 Lecture 12 March 4, 2013 Topics: Lexical scope, dynamic scope, closures

CSci 4223 Lecture 12 March 4, 2013 Topics: Lexical scope, dynamic scope, closures 1 Lexical Scope SML, and nearly all modern languages, follow the Rule of Lexical Scope: the body of a function is evaluated

### Consider the following EBNF definition of a small language:

xercise 1: Consider the following BNF definition of a small language: program ::= + decl ::= vardecl ::= "var" ":" "=" ";" procdecl ::= "procedure"

### Type Checking and Type Inference

Type Checking and Type Inference Principles of Programming Languages CSE 307 1 Types in Programming Languages 2 Static Type Checking 3 Polymorphic Type Inference Version: 1.8 17:20:56 2014/08/25 Compiled

### Intro. Scheme Basics. scm> 5 5. scm>

Intro Let s take some time to talk about LISP. It stands for LISt Processing a way of coding using only lists! It sounds pretty radical, and it is. There are lots of cool things to know about LISP; if

### Design Issues. Subroutines and Control Abstraction. Subroutines and Control Abstraction. CSC 4101: Programming Languages 1. Textbook, Chapter 8

Subroutines and Control Abstraction Textbook, Chapter 8 1 Subroutines and Control Abstraction Mechanisms for process abstraction Single entry (except FORTRAN, PL/I) Caller is suspended Control returns

### 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

### DO NOT OPEN UNTIL INSTRUCTED

CS 345 - Programming Languages Fall 2010 MIDTERM #1 October 5, 2010 DO NOT OPEN UNTIL INSTRUCTED YOUR NAME: Collaboration policy No collaboration is permitted on this midterm. Any cheating (e.g., submitting

### CSE 130 [Winter 2014] Programming Languages

CSE 130 [Winter 2014] Programming Languages Higher-Order Functions! Ravi Chugh! Jan 23 Today s Plan A little more practice with recursion Base Pattern Base Expression Induction Pattern Induction Expression

### Debugging in LISP. trace causes a trace to be printed for a function when it is called

trace causes a trace to be printed for a function when it is called ;;; a function that works like reverse (defun rev (list) (cons (first (last list)) (rev (butlast list)))) USER: (trace rev) ; note trace

### Products and Records

Products and Records Michael P. Fourman February 2, 2010 1 Simple structured types Tuples Given a value v 1 of type t 1 and a value v 2 of type t 2, we can form a pair, (v 1, v 2 ), containing these values.

### A LISP Interpreter in ML

UNIVERSITY OF OSLO Department of Informatics A LISP Interpreter in ML Mandatory Assignment 1 INF3110 September 21, 2009 Contents 1 1 Introduction The purpose of this assignment is to write an interpreter,

### The compilation process is driven by the syntactic structure of the program as discovered by the parser

Semantic Analysis The compilation process is driven by the syntactic structure of the program as discovered by the parser Semantic routines: interpret meaning of the program based on its syntactic structure

### Announcement. Overview. LISP: A Quick Overview. Outline of Writing and Running Lisp.

Overview Announcement Announcement Lisp Basics CMUCL to be available on sun.cs. You may use GNU Common List (GCL http://www.gnu.org/software/gcl/ which is available on most Linux platforms. There is also

### SMURF Language Reference Manual Serial MUsic Represented as Functions

SMURF Language Reference Manual Serial MUsic Represented as Functions Richard Townsend, Lianne Lairmore, Lindsay Neubauer, Van Bui, Kuangya Zhai {rt2515, lel2143, lan2135, vb2363, kz2219}@columbia.edu

### 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

### Review. CS152: Programming Languages. Lecture 11 STLC Extensions and Related Topics. Let bindings (CBV) Adding Stuff. Booleans and Conditionals

Review CS152: Programming Languages Lecture 11 STLC Extensions and Related Topics e ::= λx. e x ee c v ::= λx. e c (λx. e) v e[v/x] e 1 e 2 e 1 e 2 τ ::= int τ τ Γ ::= Γ,x : τ e 2 e 2 ve 2 ve 2 e[e /x]:

### CSE341 Spring 2016, Midterm Examination April 29, 2016

CSE341 Spring 2016, Midterm Examination April 29, 2016 Please do not turn the page until 10:30. Rules: The exam is closed-book, closed-note, etc. except for one side of one 8.5x11in piece of paper. Please

### 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

### Pattern Matching for Scheme

Pattern Matching for Scheme Andrew K. Wright March 1996 Department of Computer Science MS 132 Rice University 6100 Main Street Houston, Texas 77005-1892 Contents 1 Match 1 1.1 Definition... 1 1.1.1 Patterns...

### 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

### 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

### Inductive Data Types

Inductive Data Types Lars-Henrik Eriksson Functional Programming 1 Original slides by Tjark Weber Lars-Henrik Eriksson (UU) Inductive Data Types 1 / 42 Inductive Data Types Today Today New names for old

### Comp 204: Computer Systems and Their Implementation. Lecture 25a: Revision Lectures (separate questions and answers)

Comp 204: Computer Systems and Their Implementation Lecture 25a: Revision Lectures (separate questions and answers) 1 Today Here are a sample of questions that could appear in the exam Please LET ME KNOW

### CA4003 Compiler Construction Assignment Language Definition

CA4003 Compiler Construction Assignment Language Definition David Sinclair 2017-2018 1 Overview The language is not case sensitive. A nonterminal, X, is represented by enclosing it in angle brackets, e.g.

Advanced Systems Programming Introduction to C++ Martin Küttler September 19, 2017 1 / 18 About this presentation This presentation is not about learning programming or every C++ feature. It is a short

### CS Lecture 5: Pattern Matching. Prof. Clarkson Fall Today s music: Puff, the Magic Dragon by Peter, Paul & Mary

CS 3110 Lecture 5: Pattern Matching Prof. Clarkson Fall 2014 Today s music: Puff, the Magic Dragon by Peter, Paul & Mary Review Features so far: variables, operators, let expressions, if expressions, functions

### Informatica 3 Syntax and Semantics

Informatica 3 Syntax and Semantics Marcello Restelli 9/15/07 Laurea in Ingegneria Informatica Politecnico di Milano Introduction Introduction to the concepts of syntax and semantics Binding Variables Routines

### CSE 505. Lecture #9. October 1, Lambda Calculus. Recursion and Fixed-points. Typed Lambda Calculi. Least Fixed Point

Lambda Calculus CSE 505 Lecture #9 October 1, 2012 Expr ::= Var λ Var. Expr (Expr Expr) Key Concepts: Bound and Free Occurrences Substitution, Reduction Rules: α, β, η Confluence and Unique Normal Form

### General Computer Science (CH ) Fall 2016 SML Tutorial: Practice Problems

General Computer Science (CH08-320101) Fall 2016 SML Tutorial: Practice Problems November 30, 2016 Abstract This document accompanies the traditional SML tutorial in GenCS. It contains a sequence of simple

### Standard ML. Curried Functions. ML Curried Functions.1

Standard ML Curried Functions ML Curried Functions.1 Curried Functions Side Note: Infix function declaration o Curried Function declaration o Declaring via "fun" o Function Calling Order o Examples o Mixing

### CSC324 Functional Programming Typing, Exceptions in ML

CSC324 Functional Programming Typing, Exceptions in ML Afsaneh Fazly 1 Winter 2013 1 with many thanks to Anya Tafliovich, Gerald Penn, Sheila McIlraith, Wael Aboelsaddat, Tony Bonner, Eric Joanis, Suzanne

### Functional Languages and Higher-Order Functions

Functional Languages and Higher-Order Functions Leonidas Fegaras CSE 5317/4305 L12: Higher-Order Functions 1 First-Class Functions Values of some type are first-class if They can be assigned to local variables

### Meanings of syntax. Norman Ramsey Geoffrey Mainland. COMP 105 Programming Languages Tufts University. January 26, 2015

Meanings of syntax Norman Ramsey Geoffrey Mainland COMP 105 Programming Languages Tufts University January 26, 2015 (COMP 105) Meanings of syntax January 26, 2015 1 / 33 What is the meaning of a while

### Type Checking. Chapter 6, Section 6.3, 6.5

Type Checking Chapter 6, Section 6.3, 6.5 Inside the Compiler: Front End Lexical analyzer (aka scanner) Converts ASCII or Unicode to a stream of tokens Syntax analyzer (aka parser) Creates a parse tree

### How does ML deal with +?

How does ML deal with +? Moscow ML version 2.00 (June 2000) - op +; > val it = fn : int * int -> int - 1 + 1; > val it = 2 : int - 1.0 + 1.0; > val it = 2.0 : real - false + false;! Overloaded + cannot

### 15 212: Principles of Programming. Some Notes on Continuations

15 212: Principles of Programming Some Notes on Continuations Michael Erdmann Spring 2011 These notes provide a brief introduction to continuations as a programming technique. Continuations have a rich

### Project 5 - The Meta-Circular Evaluator

MASSACHVSETTS INSTITVTE OF TECHNOLOGY Department of Electrical Engineering and Computer Science 6.001 Structure and Interpretation of Computer Programs Spring Semester, 2005 Project 5 - The Meta-Circular

### Types. Type checking. Why Do We Need Type Systems? Types and Operations. What is a type? Consensus

Types Type checking What is a type? The notion varies from language to language Consensus A set of values A set of operations on those values Classes are one instantiation of the modern notion of type

### Example. program sort; var a : array[0..10] of integer; procedure readarray; : function partition (y, z :integer) :integer; var i, j,x, v :integer; :

Runtime Environment Relationship between names and data objects (of target machine) Allocation & de-allocation is managed by run time support package Each execution of a procedure is an activation of the

### B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University

Unit 1 Programming Language and Overview of C 1. State whether the following statements are true or false. a. Every line in a C program should end with a semicolon. b. In C language lowercase letters are

### PROGRAMMING IN HASKELL. Chapter 2 - First Steps

PROGRAMMING IN HASKELL Chapter 2 - First Steps 0 The Hugs System Hugs is an implementation of Haskell 98, and is the most widely used Haskell system; The interactive nature of Hugs makes it well suited

### Programming Languages and Compilers (CS 421)

Programming Languages and Compilers (CS 421) Elsa L Gunter 2112 SC, UIUC https://courses.engr.illinois.edu/cs421/fa2017/cs421d Based in part on slides by Mattox Beckman, as updated by Vikram Adve and Gul

### Types, Type Inference and Unification

Types, Type Inference and Unification Mooly Sagiv Slides by Kathleen Fisher and John Mitchell Cornell CS 6110 Summary (Functional Programming) Lambda Calculus Basic ML Advanced ML: Modules, References,

### Scheme. Functional Programming. Lambda Calculus. CSC 4101: Programming Languages 1. Textbook, Sections , 13.7

Scheme Textbook, Sections 13.1 13.3, 13.7 1 Functional Programming Based on mathematical functions Take argument, return value Only function call, no assignment Functions are first-class values E.g., functions

### Semantic Processing (Part 2)

Semantic Processing (Part 2) All Projects Due: Fray 12-2-05, Noon Final: Monday, December 5, 2005, 10:15-12:05 Comprehensive 1 Recursive Type Definitions MyRec is record f1: integer; f2: array of MyRec;

### CSCI 3155: Principles of Programming Languages Exam preparation #1 2007

CSCI 3155: Principles of Programming Languages Exam preparation #1 2007 Exercise 1. Consider the if-then-else construct of Pascal, as in the following example: IF 1 = 2 THEN PRINT X ELSE PRINT Y (a) Assume

### Lecture 19: Signatures, Structures, and Type Abstraction

15-150 Lecture 19: Signatures, Structures, and Type Abstraction Lecture by Dan Licata March 27, 2012 In these lectures, we will discuss the use of the ML module system for structuring large programs. Key

### Lecture 4: The Declarative Sequential Kernel Language. September 5th 2011

Lecture 4: The Declarative Sequential Kernel Language September 5th 2011 1 Lecture Outline Syntactic Analysis of Programs contd Scanning contd The Declarative Kernel Language Introduction Syntax of the

### Today's Topics. CISC 458 Winter J.R. Cordy

Today's Topics Last Time Semantics - the meaning of program structures Stack model of expression evaluation, the Expression Stack (ES) Stack model of automatic storage, the Run Stack (RS) Today Managing

### CSE 130: Programming Languages. Polymorphism. Ranjit Jhala UC San Diego

CSE 130: Programming Languages Polymorphism Ranjit Jhala UC San Diego Q: What is the value of res? let f g = let x = 0 in g 2 let x = 100 let h y = x + y let res = f h (a) 0 (b) 2 (c) 100 (d) 102 (e) 12

### CSCI-GA Final Exam

CSCI-GA 2110-003 - Final Exam Instructor: Thomas Wies Name: Sample Solution ID: You have 110 minutes time. There are 7 assignments and you can reach 110 points in total. You can solve the exercises directly

### Objectives. Chapter 4: Control Structures I (Selection) Objectives (cont d.) Control Structures. Control Structures (cont d.) Relational Operators

Objectives Chapter 4: Control Structures I (Selection) In this chapter, you will: Learn about control structures Examine relational and logical operators Explore how to form and evaluate logical (Boolean)

### Redex: Practical Semantics Engineering

Redex: Practical Semantics Engineering Version 4.2.3 Robert Bruce Findler and Casey Klein December 1, 2009 PLT Redex consists of a domain-specific language for specifying reduction semantics, plus a suite

### Functional Programming

Functional Programming A Brief Introduction to Standard ML Arnd Poetzsch-Heffter Software Technology Group Fachbereich Informatik Technische Universität Kaiserslautern Sommersemester 2010 Arnd Poetzsch-Heffter

### 22c:111 Programming Language Concepts. Fall Types I

22c:111 Programming Language Concepts Fall 2008 Types I Copyright 2007-08, The McGraw-Hill Company and Cesare Tinelli. These notes were originally developed by Allen Tucker, Robert Noonan and modified

### Types for References, Exceptions and Continuations. Review of Subtyping. Γ e:τ τ <:σ Γ e:σ. Annoucements. How s the midterm going?

Types for References, Exceptions and Continuations Annoucements How s the midterm going? Meeting 21, CSCI 5535, Spring 2009 2 One-Slide Summary Review of Subtyping If τ is a subtype of σ then any expression

### CS1 Lecture 5 Jan. 26, 2018

CS1 Lecture 5 Jan. 26, 2018 HW1 due Monday, 9:00am. Notes: Do not write all the code at once (for Q1 and 2) before starting to test. Take tiny steps. Write a few lines test... add a line or two test...

### Local defini1ons. Func1on mul1ples- of

Local defini1ons The func1ons and special forms we ve seen so far can be arbitrarily nested except define and check- expect. So far, defini.ons have to be made at the top level, outside any expression.

### 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:

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