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

Save this PDF as:

Size: px
Start display at page:

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

## Transcription

1 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, ML tries to find a unique type for the epression meaningful type for the epr 3. ML evaluates epression to compute value Of the same type found in step 2 Tail Recursion: Factorial let rec fact n = if n<=0 then 1 else n * fact (n-1);; 2 How does it eecute? let rec fact n = if n<=0 then 1 else n * fact (n-1);; fac 3;; 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 3 4 Tail recursive factorial Tail recursive factorial let fact = let fact = let rec helper curr = if <= 0 then curr else helper ( - 1) ( * curr) in helper 1;; 5 6 1

2 How does it eecute? Tail recursion let fact = let rec helper curr = if <= 0 then curr else helper ( - 1) ( * curr) in helper 1;; 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 fact 3;; Why do we care about tail recursion? it turns out that tail recursion can be optimized into a simple loop 7 8 Compiler can optimize! Tail recursion summary let fact = let rec helper curr = if <= 0 fact() { curr := 1; while (1) { if ( <= 0) Tail recursive calls can be optimized as a jump then curr else helper ( - 1) ( * curr) in helper 1;; } then { return curr } else { := 1; curr := ( * curr) } Part of the language specification of some languages (ie: you can count on the compiler to optimize tail recursive calls) recursion! Loop! 9 10 Base Types Base Type: int Epressions built from sub-epressions Types computed from types of sub-epressions Values computed from values of sub-epressions 2

3 Base Type: int 2; 2 i i:int i ) i Base Type: float e r:float r ) r 2+3; 5 e1 + e2 e 1 :int e 2 :int e 1 +e 2 :int e1+e2)v1+v e1 +. e2 e 1 :float e 1 :float e 1 +.e 2 :float e1+.e2)v1+.v2 7-4; 3 e1 - e2 e 1 :int e 2 :int e 1 -e 2 :int e1-e2)v1-v e1 -. e2 e 1 :float e 2 :float e 1 -.e 2 :float e1-.e2)v1-.v2 (2+3)*(7-4); 15 e1 * e2 e 1 :int e 2 :int e 1 * e 2 :int e1*e2)v1*v2 ( ) /. ( ) e1 /. e2 e 1 :float e 2 :float e 1 /.e 2 :float e1/.e2)v1/.v2 Epressions built from sub-epressions Types computed from types of sub-epressions Values computed from values of sub-epressions Epressions built from sub-epressions Types computed from types of sub-epressions Values computed from values of sub-epressions Base Type: string ab ab s s:string s ) s 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<e2 ) v1<v2 ab ^ cd abcd e1^e2 e 1 :string e 2 :string e 1^e 2 :string e1^e2)v1^v2 not(2<3) ( ab = cd ) false false not e e1 = e2 e : bool not e : bool e 1 :T e 2 :T e 1 =e 2 : bool e ) v not e ) not v e1=e2 ) v1=v2 Epressions built from sub-epressions Types computed from types of sub-epressions Values computed from values of sub-epressions not (2<3) && ( ab = cd ) false e1 && e2 e 1 :bool e 2 :bool e 1 &&e 2 :bool e1&&e2) v1 && v2 Base Type: bool Equality testing is built-in for all epr,values,types but compared epressions must have same type ecept for? function values why? ( ab = cd ) false e1 = e2 e 1 :T e 2 :T e 1 =e 2 : bool e1=e2 ) v1=v2 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 Epressions built from sub-epressions Types computed from types of sub-epression If a sub-epression is not well-typed then whole epression is not well-typed 0 * (2 + a ); 3

4 Comple types: Tuples Comple types: Tuples (2+2, 7>8); (4,false) int * bool (2+2, 7>8); (4,false) int * bool e1:t1 e2:t2 (e 1,e 2 ) : T1 * T2 (e1,e2)) (v1,v2) Comple types: Tuples Can be of any fied size (9-3, ab ^ cd,7>8) (6, abcd, false) (int * string * bool) Comple types: Records {name= sarah ; age=31; pass=false} { name : string, age : int, pass : bool} Records are tuples with named elements e1:t1 e2:t2 en: Tn (e1,e2,,en) : T1 * T2* * Tn en ) vn (e1,e2,,en)) (v1,v2,,vn) {name= sarah ;age=31;pass=false}.age 31 int Elements can have different types Tuples can be nested in other tuples {age=31;name= sarah ;pass=false}.age {age=31;name= sarah ;pass=false}.pass 31 false int bool But wait Comple types: Lists All evaluation rules look like: e1 OP e2 ) v1 OP v2 [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) 4

5 Comple types: Lists Comple types: Lists [] []: a list [] ) [] [e1;e2;e3; ] e1:t e2: T e3: T [e1;e2;e3; ] : T list e3)v3 [e1;e2; ] ) [v1;v2; ] All elements have the same type [1; pq ] Comple types: list..construct Comple 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 Comple types: list construct Comple types: list deconstruct Append operator [1;2;3;4] int list Reading the elements of a list: Two operators : hd (head) and tl (tail) e1:t list e2: T list : T list e1)v1 e2 ) v2 ) [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 b ; cd ]; [ a ; b ; cd ] hd [ a ; b ; cd ] a string tl [ a ; b ; cd ] [ b ; cd ] string list b ; cd ]; Can only append lists of the same type [(1, a );(7, c )] [[];[1;2;3];[4;5]] hd [(1, a );(7, c )](1, a ) Int * string hd [[];[1;2;3];4;5] 1 int list tl [(1, a );(7, c )] [(7; c )] (int * string) list tl [[];[1;2;3];4;5] [2;3;4;5] int list list 5

6 List: Heads and Tails 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 Recap Epressions (Synta) Compile-time Static Eec-time Dynamic Types Values (Semantics) Recap Integers: +,-,* floats: +,-,* Booleans: =,<, andalso, orelse, not Strings: ^ 1. Programmer enters epression 2. ML checks if epression is well-typed Using a precise set of rules, ML tries to find a unique type for the epression meaningful type for the epr 3. ML evaluates epression to compute value Of the same type found in step 2 Tuples, Records: #i Fied number of values, of different types Lists: Unbounded number of values, of same type If-then-else epressions if (1 < 2) then 5 else 10 5 if (1 < 2) then [ ab, cd ] else [ ] If-then-else is also an epression! Can use any epression in then, else branch if e1 then e2 else e3 int [ ab, cd ] string list If-then-else epressions if (1 < 2) then 5 else 10 5 if (1 < 2) then [ ab, cd ] else [ ] If-then-else is also an epression! Can use any epression in then, else branch if e1 then e2 else e3 int [ ab, cd ] 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 6

7 If-then-else epressions if (1 < 2) then [1;2] else 5 if false then [1;2] else 5 then-subep, else-subep must have same type! which is the type of resulting epression e1 : bool e2: T e3: T if e1 then e2 else e3 : T If-then-else epressions e1 : bool e2: T e3: T if e1 then e2 else e3 : T Then-subep, Else-subep must have same type! Equals type of resulting epression 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 ]) 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 # let = 2+2;; val : int = 4 # let y = * * ;; val y : int = 64 # let z = [;y;+y];; val z : int list = [4;64;68] Later declared epressions can use Most recent bound value used for evaluation Sounds like C/Java? NO! Environments ( Phone Book ) How ML deals with variables Variables = names Values = phone number y z 6 [4;64;68] : int list 8 : int 7

8 Environments and Evaluation ML begins in a top-level environment Some names bound let = e;; ML program = Sequence of variable bindings Program evaluated by evaluating bindings in order 1. Evaluate epr e in current env to get value v : t 2. Etend env to bind to v : t (Repeat with net binding) Environments Phone book Variables = names Values = phone number 1. Evaluate: Find and use most recent value of variable 2. Etend: Add new binding at end of phone book Eample Environments # let = 2+2;; val : int = 4 # let y = * * ;; val y : int = 64 # let z = [;y;+y];; val z : int list = [4;64;68] # let = + ;; val : int = 8 New binding! y y z y z 6 6 [4;64;68] : int list 6 [4;64;68] : int list 8 : int 1. Evaluate: Use most recent bound value of var 2. Etend: Add new binding at end How is this different from C/Java s store? # let = 2+2;; val : int = 4 # let f = fun y -> + y; val f : int -> int = fn # let = + ; val : int = 8 # f 0; val it : int = 4 f fn <code, >: int->int New binding: No change or mutation Old binding frozen in f Environments Environments 1. Evaluate: Use most recent bound value of var 2. Etend: Add new binding at end How is this different from C/Java s store? 1. Evaluate: Use most recent bound value of var 2. Etend: Add new binding at end How is this different from C/Java s store? # let = 2+2;; val : int = 4 # let = 2+2;; val : int = 4 # let f = fun y -> + y; val f : int -> int = fn # let = + ; val : int = 8 # f 0; val it : int = 4 f fn <code, >: int->int f fn <code, >: int->int 8 : int # let f = fun y -> + y; val f : int -> int = fn # let = + ; val : int = 8 # f 0; val it : int = 4 Binding used to eval (f ) f fn <code, >: int->int 8 : int Binding for subsequent 8

9 Cannot change the world Cannot assign to variables Can etend 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 = 2+2;; val : int = 4 # let f = fun y -> + y;; val f : int -> int = fn # let = + ;; val : int = 8; # f 0;; val it : int = 4 Binding used to eval (f ) f fn <code, >: int->int 8 : int Binding for subsequent 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 Eamples 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, etendable systems Recap: Environments Phone book Variables = names Values = phone number 1. Evaluate: Find and use most recent value of variable 2. Etend: let = e ;; Add new binding at end of phone book Net: Functions Functions Functions are values, can bind using let epr Epressions Values let fname = fun -> e ;; Types 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 = e ;; Occurences of fname inside e bound to this definition let rec fac = if <=1 then 1 else *fac (-1) 9

10 Functions Type Functions Type e1 : T2 -> T e1 e2 : T e2: T2 Functions Values Functions Values Two questions about function values: Two questions about function values: What is the value: What is the value: 1. of a function? 1. of a function? 2. of a function application (call)? (e1 e2) 2. of a function application (call)? (e1 e2) Values of functions: Closures Values of function application Body epression 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 = 2+2;; val : int = 4 # let f = fun y -> + y;; val f : int -> int = fn # let = + ;; val : int = 8 # f 0;; val it : int = 4 Binding used to eval (f ) f fn <code, >: int->int 8 : int Binding for subsequent 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 + body e), env is E 2. Evaluate e2 in current env to get (argument) v2 3. Evaluate body e in env E etended by binding to v2 10

11 Eample 1 let = 1;; let f y = + y;; let = 2;; let y = 3;; f ( + y);; Eample 1 let = 1;; let f y = + y;; let = 2;; let y = 3;; f ( + y);; Eample 2 let = 1;; let f y = let = 2 in fun z -> + y + z ;; let = 100;; let g = (f 4);; let y = 100;; (g 1);; Eample 2 let = 1;; let f y = let = 2 in fun z -> + y + z ;; let = 100;; let g = (f 4);; let y = 100;; (g 1);; Eample 3 let f g = let = 0 in g 2 ;; let = 100;; let h y = + y;; f h;; Static/Leical Scoping For each occurrence of a variable, Unique place in program tet where variable defined Most recent binding in environment Static/Leical: Determined from the program tet Without eecuting 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 11

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

### Side note: Tail Recursion. Begin at the beginning. Side note: Tail Recursion. Base Types. Base Type: int. Base Type: int

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,

### Begin at the beginning

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

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

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

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

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

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

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

### News. Programming Languages. Complex types: Lists. Recap: ML s Holy Trinity. CSE 130: Spring 2012

News CSE 130: Spring 2012 Programming Languages On webpage: Suggested HW #1 PA #1 (due next Fri 4/13) Lecture 2: A Crash Course in ML Please post questions to Piazza Ranjit Jhala UC San Diego Today: A

### Plan (next 4 weeks) 1. Fast forward. 2. Rewind. 3. Slow motion. Rapid introduction to what s in OCaml. Go over the pieces individually

Plan (next 4 weeks) 1. Fast forward Rapid introduction to what s in OCaml 2. Rewind 3. Slow motion Go over the pieces individually History, Variants Meta Language Designed by Robin Milner @ Edinburgh Language

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

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

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

### Recap: ML s Holy Trinity. Story So Far... CSE 130 Programming Languages. Datatypes. A function is a value! Next: functions, but remember.

CSE 130 Programming Languages Recap: ML s Holy Trinity Expressions (Syntax) Exec-time Dynamic Values (Semantics) Datatypes Compile-time Static Types Ranjit Jhala UC San Diego 1. Programmer enters expression

### Programming Languages

CSE 130 : Winter 2013 Programming Languages Lecture 3: Crash Course, Datatypes Ranjit Jhala UC San Diego 1 Story So Far... Simple Expressions Branches Let-Bindings... Today: Finish Crash Course Datatypes

### Processadors de Llenguatge II. Functional Paradigm. Pratt A.7 Robert Harper s SML tutorial (Sec II)

Processadors de Llenguatge II Functional Paradigm Pratt A.7 Robert Harper s SML tutorial (Sec II) Rafael Ramirez Dep Tecnologia Universitat Pompeu Fabra Paradigm Shift Imperative Paradigm State Machine

### Lambda Calculus.

Lambda Calculus Oded Padon & Mooly Sagiv (original slides by Kathleen Fisher, John Mitchell, Shachar Itzhaky, S. Tanimoto, Stephen A. Edwards) Benjamin Pierce Types and Programming Languages http://www.cs.cornell.edu/courses/cs3110/2008fa/recitations/rec26.html

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

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

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

### CMSC 336: Type Systems for Programming Languages Lecture 4: Programming in the Lambda Calculus Acar & Ahmed 22 January 2008.

CMSC 336: Type Systems for Programming Languages Lecture 4: Programming in the Lambda Calculus Acar & Ahmed 22 January 2008 Contents 1 Announcements 1 2 Solution to the Eercise 1 3 Introduction 1 4 Multiple

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

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

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

### CS109A ML Notes for the Week of 1/16/96. Using ML. ML can be used as an interactive language. We. shall use a version running under UNIX, called

CS109A ML Notes for the Week of 1/16/96 Using ML ML can be used as an interactive language. We shall use a version running under UNIX, called SML/NJ or \Standard ML of New Jersey." You can get SML/NJ by

### Programming Languages. Next: Building datatypes. Suppose I wanted. Next: Building datatypes 10/4/2017. Review so far. Datatypes.

Review so far Programming Languages Expressions Values Datatypes Types Many kinds of expressions: 1. Simple 2. Variables 3. Functions Review so far We ve seen some base types and values: Integers, Floats,

### Programming Languages. Datatypes

Programming Languages Datatypes Review so far Expressions Values Types Many kinds of expressions: 1. Simple 2. Variables 3. Functions Review so far We ve seen some base types and values: Integers, Floats,

### Program Flow. Instructions and Memory. Why are these 16 bits? C code. Memory. a = b + c. Machine Code. Memory. Assembly Code.

Instructions and Memory C code Why are these 16 bits? a = b + c Assembly Code ldr r0, [sp, #4] ldr adds r1, [sp] r0, r0, r1 str r0, [sp, #8] Machine Code 09801 09900 01840 09002 Memory 0 0 0 0 0 0 0 1

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

### Redefinition of an identifier is OK, but this is redefinition not assignment; Thus

Redefinition of an identifier is OK, but this is redefinition not assignment; Thus val x = 100; val x = (x=100); is fine; there is no type error even though the first x is an integer and then it is a boolean.

### Booleans (aka Truth Values) Programming Languages and Compilers (CS 421) Booleans and Short-Circuit Evaluation. Tuples as Values.

Booleans (aka Truth Values) Programming Languages and Compilers (CS 421) Elsa L Gunter 2112 SC, UIUC https://courses.engr.illinois.edu/cs421/fa2017/cs421d # true;; - : bool = true # false;; - : bool =

### Data Types The ML Type System

7 Data Types 7.2.4 The ML Type System The following is an ML version of the tail-recursive Fibonacci function introduced Fibonacci function in ML in Section 6.6.1: EXAMPLE 7.96 1. fun fib (n) = 2. let

### Dialects of ML. CMSC 330: Organization of Programming Languages. Dialects of ML (cont.) Features of ML. Functional Languages. Features of ML (cont.

CMSC 330: Organization of Programming Languages OCaml 1 Functional Programming Dialects of ML ML (Meta Language) Univ. of Edinburgh,1973 Part of a theorem proving system LCF The Logic of Computable Functions

### Lists. Adrian Groza. Department of Computer Science Technical University of Cluj-Napoca

Lists Adrian Groza Department of Computer Science Technical University of Cluj-Napoca Recall... Parameter evaluation Call-by-value Call-by-name Call-by-need Functions Infix operators Local declarations,

### Programming Languages

What about more complex data? CSE 130 : Fall 2012 Programming Languages Expressions Values Lecture 3: Datatypes Ranjit Jhala UC San Diego Types Many kinds of expressions: 1. Simple 2. Variables 3. Functions

### More eamples with half half(0) handle Zero => 1000; > val it = 1000 : int half(1) handle Zero => 1000; > ncaght eception Odd half(0) handle Zero => 10

Lectre 4 0 More eamples with half half(0) handle Zero => 1000; > val it = 1000 : int half(1) handle Zero => 1000; > ncaght eception Odd half(0) handle Zero => 1000 Odd => 1001; > val it = 1000 : int half(3)

### Chapter 3 Linear Structures: Lists

Plan Chapter 3 Linear Structures: Lists 1. Lists... 3.2 2. Basic operations... 3.4 3. Constructors and pattern matching... 3.5 4. Polymorphism... 3.8 5. Simple operations on lists... 3.11 6. Application:

### CMSC 330: Organization of Programming Languages. Rust Basics

CMSC 330: Organization of Programming Languages Rust Basics CMSC330 Spring 2018 1 Organization It turns out that a lot of Rust has direct analogues in OCaml So we will introduce its elements with comparisons

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

### Chapter 3 Linear Structures: Lists

Plan Chapter 3 Linear Structures: Lists 1. Two constructors for lists... 3.2 2. Lists... 3.3 3. Basic operations... 3.5 4. Constructors and pattern matching... 3.6 5. Simple operations on lists... 3.9

### Lecture Notes on Lisp A Brief Introduction

Why Lisp? Lecture Notes on Lisp A Brief Introduction Because it s the most widely used AI programming language Because Prof Peng likes using it Because it s good for writing production software (Graham

### COSE212: Programming Languages. Lecture 3 Functional Programming in OCaml

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

### Announcements. Scope, Function Calls and Storage Management. Block Structured Languages. Topics. Examples. Simplified Machine Model.

CS 242 2007 Scope, Function Calls and Storage Management John Mitchell Announcements Homework Returned in class Wed; afterwards in 4 th Floor Gates Cabinet SCPD students: attach routing slip, will be returned

### CMSC330 Fall 2016 Midterm #1 2:00pm/3:30pm

CMSC330 Fall 2016 Midterm #1 2:00pm/3:30pm Name: Discussion Time: 10am 11am 12pm 1pm 2pm 3pm TA Name (Circle): Alex Austin Ayman Brian Damien Daniel K. Daniel P. Greg Tammy Tim Vitung Will K. Instructions

### A Programming Language. A different language g is a different vision of life. CSE 130 : Spring Two variables. L1: x++; y--; (y=0)?

CSE 130 : Spring 2010 Programming Languages Lecture 1: Hello, world. Ranjit Jhala UC San Diego A Programming Language Two variables x,y Three operations x++ x-- (x=0)? L1:L2; L1: x++; y--; (y=0)?l2:l1

### APS105. Modularity. C pre-defined functions 11/5/2013. Functions. Functions (and Pointers) main. Modularity. Math functions. Benefits of modularity:

APS105 Functions (and Pointers) Functions Tetbook Chapter5 1 2 Modularity Modularity Break a program into manageable parts (modules) Modules interoperate with each other Benefits of modularity: Divide-and-conquer:

### Principles of Programming Languages COMP251: Functional Programming in Scheme (and LISP)

Principles of Programming Languages COMP251: Functional Programming in Scheme (and LISP) Prof. Dekai Wu Department of Computer Science and Engineering The Hong Kong University of Science and Technology

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

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

### 1998 Midterm and Solutions

6.821 Programming Languages Handout Fall 2002 MASSACHVSETTS INSTITVTE OF TECHNOLOGY Department of Electrical Engineering and Compvter Science 1998 Midterm and Solutions There are four problems on this

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

### Functional Programming

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

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

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

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

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

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

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

### Verification of an ML compiler. Lecture 3: Closures, closure conversion and call optimisations

Verification of an ML compiler Lecture 3: Closures, closure conversion and call optimisations Marktoberdorf Summer School MOD 2017 Magnus O. Myreen, Chalmers University of Technology Implementing the ML

### Principles of Programming Languages

Principles of Programming Languages Lecture 08 Control Semantics & Continuations Semantics of Control Flow Sequencers: commands that cause control transfers:! goto! return! exit! break! continue! resultis

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

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

### Implementing Subprograms

1 Implementing Subprograms CS 315 Programming Languages Pinar Duygulu Bilkent University CS315 Programming Languages Pinar Duygulu The General Semantics of Calls and Returns 2 The subprogram call and return

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

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

### A list is a finite sequence of elements. Elements may appear more than once

Standard ML Lists ML Lists.1 Lists A list is a finite sequence of elements. [3,5,9] ["a", "list" ] [] Elements may appear more than once [3,4] [4,3] [3,4,3] [3,3,4] Elements may have any type. But all

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

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

### A Functional Space Model. COS 326 David Walker Princeton University

A Functional Space Model COS 326 David Walker Princeton University Data type representations: Last Time type tree = Leaf Node of int * tree * tree Leaf: Node(i, left, right): 0 Node 3 left right This Time

### SI232 Set #20: Laundry, Co-dependency, and other Hazards of Modern (Architecture) Life. Chapter 6 ADMIN. Reading for Chapter 6: 6.1,

SI232 Set #20: Laundry, Co-dependency, and other Hazards of Modern (Architecture) Life Chapter 6 ADMIN ing for Chapter 6: 6., 6.9-6.2 2 Midnight Laundry Task order A 6 PM 7 8 9 0 2 2 AM B C D 3 Smarty

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

### CS 342 Lecture 7 Syntax Abstraction By: Hridesh Rajan

CS 342 Lecture 7 Syntax Abstraction By: Hridesh Rajan 1 Reading SICP, page 11-19, Section 1.1.6 Little Schemer, Chapter 2 2 The Idea of Syntax Abstraction Problem. Often programming tasks are repetitive,

### Names and Functions. Chapter 2

Chapter 2 Names and Functions So far we have built only tiny toy programs. To build bigger ones, we need to be able to name things so as to refer to them later. We also need to write expressions whose

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

### Scheme as implemented by Racket

Scheme as implemented by Racket (Simple view:) Racket is a version of Scheme. (Full view:) Racket is a platform for implementing and using many languages, and Scheme is one of those that come out of the

### Fundamentals of Artificial Intelligence COMP221: Functional Programming in Scheme (and LISP)

Fundamentals of Artificial Intelligence COMP221: Functional Programming in Scheme (and LISP) Prof. Dekai Wu Department of Computer Science and Engineering The Hong Kong University of Science and Technology

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

### InterprocStack analyzer for recursive programs with finite-type and numerical variables

InterprocStack analyzer for recursive programs with finite-type and numerical variables Bertrand Jeannet Contents 1 Invoking InterprocStack 1 2 The Simple language 2 2.1 Syntax and informal semantics.........................

### CS 11 Ocaml track: lecture 2

Today: CS 11 Ocaml track: lecture 2 comments algebraic data types more pattern matching records polymorphic types ocaml libraries exception handling Previously... ocaml interactive interpreter compiling

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

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

### An Introduction to Scheme

An Introduction to Scheme Stéphane Ducasse stephane.ducasse@inria.fr http://stephane.ducasse.free.fr/ Stéphane Ducasse 1 Scheme Minimal Statically scoped Functional Imperative Stack manipulation Specification

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

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

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

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

### CIS 120 Midterm I October 2, Name (printed): Username (login id):

CIS 120 Midterm I October 2, 2015 Name (printed): Username (login id): My signature below certifies that I have complied with the University of Pennsylvania s Code of Academic Integrity in completing this

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

### CS558 Programming Languages

CS558 Programming Languages Fall 2016 Lecture 4a Andrew Tolmach Portland State University 1994-2016 Pragmatics of Large Values Real machines are very efficient at handling word-size chunks of data (e.g.

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

### 9/21/17. Outline. Expression Evaluation and Control Flow. Arithmetic Expressions. Operators. Operators. Notation & Placement

Outline Expression Evaluation and Control Flow In Text: Chapter 6 Notation Operator evaluation order Operand evaluation order Overloaded operators Type conversions Short-circuit evaluation of conditions

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