# Closures. Mooly Sagiv. Michael Clarkson, Cornell CS 3110 Data Structures and Functional Programming

Size: px
Start display at page:

Download "Closures. Mooly Sagiv. Michael Clarkson, Cornell CS 3110 Data Structures and Functional Programming"

Transcription

1 Closures Mooly Sagiv Michael Clarkson, Cornell CS 3110 Data Structures and Functional Programming

2 Summary 1. Predictive Parsing 2. Large Step Operational Semantics (Natural) 3. Small Step Operational Semantics (SOS) 4. Lambda Calculus 5. Basic OCaml 6. Modules & References OCaml 7. Closures OCaml 8. Javascript 9. Runtime states 10. Type inference 11. Scala I 12. Scala 2

3 Formal Semantics of Functional Programs Small step operational semantics Environment Expression Environment Expression Compile into typed lambda calculus

4 Essential OCcaml sublanguage e ::= c (op) x (e 1,, e n ) C e e 1 e 2 fun x -> e let x = e 1 in e 2 match e 0 with p i -> e i

5 Evaluation of Expression Expressions evaluate to values in a dynamic environment env :: e - - > v Evaluation is meaningless if expression does not type check Values are a syntactic subset of expressions: v ::= c (op) (v 1,, v n ) C v fun x -> e

6 Dealing with Functions as Values Anonymous functions fun x-> e are values env :: (fun x -> e) --> (fun x -> e)

7 Evaluating let expressions To evaluate let x = e 1 in e 2 in environment env: 1. Evaluate the binding expression e 1 to a value v 1 in environment env env :: e 1 --> v 2. Extend the environment to bind x to v 1 env = env [x v 1 ] (newer bindings temporarily shadow older bindings) 3. Evaluate the body expression e 2 to a value v 2 in environment env env :: e 2 --> v 2 4. Return v 2

8 Compiling let expressions into Lambda Calculus let v = e1 in e2

9 Evaluating Function Application take 1 To evaluate e 1 e 2 in environment env 1. Evaluate e 2 to a value v 2 in environment env env :: e 2 --> v 2 Note: right to left order, like tuples, which matters in the presence of side effects 2. Evaluate e 1 to a value v 1 in environment env env :: e 1 --> v 1 Note that v 1 must be a function value fun x -> e 3. Extend environment to bind formal parameter x to actual value v 2 env = env [x v 2 ] 4. Evaluate body e to a value v in environment env env :: e --> v 5. Return v

10 Evaluating Function Application take 1 if env :: e2 --> v2 and env :: e1 --> (fun x -> e) and env[x v2] :: e --> v then env :: e1 e2 --> v

11 Evaluating Function Application Simple Example let f = fun x -> x in f 0 1. Evaluate binding expression fun x->x to a value in empty environment env 0 2. Extend environment to bind f to fun x->x 3. Evaluate let-body expression f 0 in environment env 1 env 1 :: f 0 --> v1 1. Evaluate 0 to a value 0 in environment env 1 2. Evaluate f to fun x -> x 3. Extend environment to bind formal parameter x to actual value 0 4. env 2 = env 1 [x 0] = [f, x 0] Evaluate the function body x in environment env 2 env 2 :: x--> 0 4. Return 0 env 1 =env 0 [f fun x -> x ] = [f fun x -> x] env 2 :: x--> 0 env 0 =[]

12 Hard Example let x = 1 in let f = fun y -> x in let x = 2 in f 0 1. What is the result of the expression? 2. What does OCaml say? 3. What do you say?

13 Hard Example Ocaml let x = 1 in let f = fun y -> x in let x = 2 in f 0 warning 26: x unused variable :- int 1

14 Why different answers? Two different rules for variable scope Rule of dynamic scope (lisp) Rule of lexical (static) scope (Ocaml, Javascript, Scheme, )

15 Dynamic Scope Rule of dynamic scope: The body of a function is evaluated in the current dynamic environment at the time the function is called, not the old dynamic environment that existed at the time the function was defined Use latest binding of x Thus return 2

16 Lexical Scope Rule of lexical scope: The body of a function is evaluated in the old dynamic environment that existed at the time the function was defined, not the current environment when the function is called Causes OCaml to use earlier binding of x hus return 1

17 Scope Rule of dynamic scope: The body of a function is evaluated in the current dynamic environment at the time the function is called, not the old dynamic environment that existed at the time the function was defined Rule of lexical scope: The body of a function is evaluated in the old dynamic environment that existed at the time the function was defined, not the current environment when the function is called In both, environment is extended to map formal parameter to actual value Why would you want one vs. the other?

18 Implementing time travel Q A How can functions be evaluated in old environments? The language implementation keeps them around as necessary A function value is really a data structure that has two parts: 1. The code 2. The environment that was current when the function was defined 1. Gives meaning to all the free variables of the function body Like a pair But you cannot access the pieces, or directly write one down in the language syntax All you can do is call it This data structure is called a function closure A function application: evaluates the code part of the closure in the environment part of the closure extended to bind the function argument

19 Hard Example Revisited [1] let x = 1 in [2] let f = fun y -> x in [3] let x = 2 in [4] let z = f 0 in z With lexical scope: Line 2 creates a closure and binds f to it: Code: fun y -> x Environment: [x 1] Line 4 calls that closure with 0 as argument In function body, y maps to 0 and x maps to 1 So z is bound to 1

20 Another Example [1] let x = 1 in [2] let f y = x + y in [3] let x = 3 in [4] let y = 4 in [5] let z = f (x + y) in z With lexical scope: 1. Creates a closure and binds f to it: Code: fun y -> x + y Environment: [x 1] 2. Line 5 env =[x 3, y 4] 3. Line 5 calls that closure with x+y=7 as argument In function body, x maps to 1 So z is bound to 8

21 Another Example [1] let x = 1 in [2] let f y = x + y in [3] let x = 3 in [4] let y = 4 in [5] let z = f (x + y) in z With dynamic scope: 1. Line 5 env =[x 3, y 4] 2. Line 5 calls that closure with x+y=7 as argument In function body, x maps to 3, so x+y maps to 10 Note that argument y shadows y from line 4 So z is bound to 10

22 Closure Notation <<code, environment>> <<fun y -> x+y, [x 1>> With lexical scoping, well-typed programs are guaranteed never to have any variables in the code body other than function argument and variables bound by closure environment

23 Evaluating Function Application take 2 To evaluate e 1 e 2 in environment env 1. Evaluate e 2 to a value v 2 in environment env env :: e 2 --> v 2 Note: right to left order, like tuples, which matters in the presence of side effects 2. Evaluate e 1 to a value v 1 in environment env env :: e 1 --> v 1 Note that v 1 must be a closure with function value fun x -> e and environment env 3. Extend environment to bind formal parameter x to actual value v 2 env = env [x v 2 ] 4. Evaluate body e to a value v in environment env env :: e --> v 5. Return v

24 Evaluating Function Application take 2 if env :: e2 --> v2 and env :: e1 --> <<fun x -> e, env >> and env [x v2] :: e --> v then env :: e1 e2 --> v

25 Evaluating Anonymous Function Application take 2 Anonymous functions fun x-> e are closures env :: (fun x -> e) --> <<fun x -> e, env>>

26 Why are Closure useful? Hides states in an elegant way Useful for Implementing objects Web programming Operated system programming Emulating control flow

27 Simple Example let startat x = let incrementby y = x + y in incrementby val startat : int -> int -> int = <fun> let closure1 = startat 3 val closure1 : int -> int = <fun> let closure2 = startat 5 val closure2 : int -> int = <fun> closure1 7 :- int =10 closure2 9 :- int =14

28 Another Example let derivative f dx = fun x -> f (x + dx) f x / dx val derivative : (int -> int) -> int -> int -> int = <fun>

29 Implementation Notes Duration of closure can be long Usually implemented with garbage collection It is possible to support lexical scopes without closure (using stack) if one of the following is forbidden: Nested scopes (C, Java) Returning a function (Algol, Pascal)

30 Lexical vs. dynamic scope Consensus after decades of programming language design is that lexical scope is the right choice Dynamic scope is convenient in some situations Some languages use it as the norm (e.g., Emacs LISP, LaTeX) Some languages have special ways to do it (e.g., Perl, Racket) But most languages just don t have it

31 Why Lexical Scope (1) Programmer can freely change names of local variables (* 1 *) let x = 1 (* 2 *) let f y = let x = y + 1 in fun z -> x+y+z (* 3 *) let x = 3 (* 4 *) let w = (f 4) 6 (* 1 *) let x = 0 (* 2 *) let f y = let q = y + 1 in fun z -> q+y+z (* 3 *) let x = 3 (* 4 *) let w = (f 4) 6

32 Why Lexical Scope (2) Type checker can prevent run-time errors (* 1 *) let x = 1 (* 2 *) let f y = let x = y + 1 in fun z -> x+y+z (* 3 *) let x = 3 (* 4 *) let w = (f 4) 6 (* 1 *) let x = 0 (* 2 *) let f y = let x = y + 1 in fun z -> x+y+z (* 3 *) let x = hi (* 4 *) let w = (f 4) 6

33 Exception Handling Resembles dynamic scope: raise e transfers control to the most recent exception handler like how dynamic scope uses most recent binding of variable

34 Where is an exception caught? Dynamic scoping of handlers Throw to most recent catch on run-time stack Dynamic scoping is not an accident User knows how to handler error Author of library function does not

35 Essential OCcaml sublanguage e ::= c (op) x (e 1,, e n ) C e e 1 e 2 fun x -> e let x = e 1 in e 2 match e 0 with p i -> e i

36 Essential OCcaml sublanguage+rec e ::= c (op) x (e 1,, e n ) C e e 1 e 2 fun x -> e let x = e 1 in e 2 match e 0 with p i -> e i let rec f x = e1 in e2

37 let rec Evaluation To evaluate let rec f x = e 1 in e 2 in environment env don t evaluate the binding expression e 1 1. Extend the environment to bind f to a recursive closure env = env [f <<f, fun x -> e 1, env>>] 2. Evaluate the body expression e 2 to a value v 2 in environment env env :: e 2 --> v 2 3. Return v 2

38 Closure in OCaml Closure conversion is an important phase of compiling many functional languages Expands on ideas we ve seen here Many optimizations possible Especially, better handling of recursive functions

39 Closures in Java Nested classes can simulate closures Used everywhere for Swing GUI! generalrules.html#innerclasses Java 8 adds higher-order functions and closures Can even think of OCaml closures as resembling Java objects: closure has a single method, the code part, that can be Invoked closure has many fields, the environment part, that can be accessed

40 Closures in C In C, a function pointer is just a code pointer, period, No environment To simulate closures, a common idiom: Define function pointers to take an extra, explicit environment argument But without generics, no good choice for type of list elements or the environment Use void* and various type casts From Linux kernel:

41 Summary Lexical scoping is natural Permit general programming style Works well with higher order functions Well understood Implemented with closures But requires long lived objects Integrated into many programming languages Some surprises (javascript)

42 Summary (Ocaml) Functional programs provide concise coding Compiled code compares with C code Successfully used in some commercial applications F#, ERLANG, Jane Street Ideas used in imperative programs Good conceptual tool Less popular than imperative programs

### Closures. Mooly Sagiv. Michael Clarkson, Cornell CS 3110 Data Structures and Functional Programming

Closures Mooly Sagiv Michael Clarkson, Cornell CS 3110 Data Structures and Functional Programming t ::= x x. t t t Call-by-value big-step Operational Semantics terms variable v ::= values abstraction x.

### The Environment Model. Nate Foster Spring 2018

The Environment Model Nate Foster Spring 2018 Review Previously in 3110: Interpreters: ASTs, evaluation, parsing Formal syntax: BNF Formal semantics: dynamic: small-step substitution model static semantics

### The Environment Model

The Environment Model Prof. Clarkson Fall 2017 Today s music: Selections from Doctor Who soundtracks by Murray Gold Review Previously in 3110: Interpreters: ASTs, evaluation, parsing Formal syntax: BNF

### CS Lecture 7: The dynamic environment. Prof. Clarkson Spring Today s music: Down to Earth by Peter Gabriel from the WALL-E soundtrack

CS 3110 Lecture 7: The dynamic environment Prof. Clarkson Spring 2015 Today s music: Down to Earth by Peter Gabriel from the WALL-E soundtrack Review Course so far: Syntax and semantics of (most of) OCaml

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

### Topics Covered Thus Far CMSC 330: Organization of Programming Languages

Topics Covered Thus Far CMSC 330: Organization of Programming Languages Names & Binding, Type Systems Programming languages Ruby Ocaml Lambda calculus Syntax specification Regular expressions Context free

### CS558 Programming Languages

CS558 Programming Languages Fall 2016 Lecture 3a Andrew Tolmach Portland State University 1994-2016 Formal Semantics Goal: rigorous and unambiguous definition in terms of a wellunderstood formalism (e.g.

### Recap: Functions as first-class values

Recap: Functions as first-class values Arguments, return values, bindings What are the benefits? Parameterized, similar functions (e.g. Testers) Creating, (Returning) Functions Iterator, Accumul, Reuse

### Every language has its own scoping rules. For example, what is the scope of variable j in this Java program?

Lexical Binding There are two ways a variable can be used in a program: As a declaration As a "reference" or use of the variable Scheme has two kinds of variable "declarations" -- the bindings of a let-expression

### CMSC 330: Organization of Programming Languages

CMSC 330: Organization of Programming Languages Type Systems, Names and Binding CMSC 330 - Spring 2013 1 Topics Covered Thus Far! Programming languages Ruby OCaml! Syntax specification Regular expressions

### CS558 Programming Languages

CS558 Programming Languages Winter 2017 Lecture 4a Andrew Tolmach Portland State University 1994-2017 Semantics and Erroneous Programs Important part of language specification is distinguishing valid from

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

### CS558 Programming Languages. Winter 2013 Lecture 3

CS558 Programming Languages Winter 2013 Lecture 3 1 NAMES AND BINDING One essential part of being a high-level language is having convenient names for things: variables constants types functions etc. classes

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

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

### Topics Covered Thus Far. CMSC 330: Organization of Programming Languages. Language Features Covered Thus Far. Programming Languages Revisited

CMSC 330: Organization of Programming Languages Type Systems, Names & Binding Topics Covered Thus Far Programming languages Syntax specification Regular expressions Context free grammars Implementation

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

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

### The role of semantic analysis in a compiler

Semantic Analysis Outline 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

### Racket. CSE341: Programming Languages Lecture 14 Introduction to Racket. Getting started. Racket vs. Scheme. Example.

Racket Next 2+ weeks will use the Racket language (not ML) and the DrRacket programming environment (not emacs) Installation / basic usage instructions on course website CSE34: Programming Languages Lecture

### Weeks 6&7: Procedures and Parameter Passing

CS320 Principles of Programming Languages Weeks 6&7: Procedures and Parameter Passing Jingke Li Portland State University Fall 2017 PSU CS320 Fall 17 Weeks 6&7: Procedures and Parameter Passing 1 / 45

### CSE 341 Section 5. Winter 2018

CSE 341 Section 5 Winter 2018 Midterm Review! Variable Bindings, Shadowing, Let Expressions Boolean, Comparison and Arithmetic Operations Equality Types Types, Datatypes, Type synonyms Tuples, Records

### Semantic Analysis. Lecture 9. February 7, 2018

Semantic Analysis Lecture 9 February 7, 2018 Midterm 1 Compiler Stages 12 / 14 COOL Programming 10 / 12 Regular Languages 26 / 30 Context-free Languages 17 / 21 Parsing 20 / 23 Extra Credit 4 / 6 Average

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

### Type Inference. Prof. Clarkson Fall Today s music: Cool, Calm, and Collected by The Rolling Stones

Type Inference Prof. Clarkson Fall 2016 Today s music: Cool, Calm, and Collected by The Rolling Stones Review Previously in 3110: Interpreters: ASTs, evaluation, parsing Formal syntax Formal semantics

### Tail Calls. CMSC 330: Organization of Programming Languages. Tail Recursion. Tail Recursion (cont d) Names and Binding. Tail Recursion (cont d)

CMSC 330: Organization of Programming Languages Tail Calls A tail call is a function call that is the last thing a function does before it returns let add x y = x + y let f z = add z z (* tail call *)

### CSE 341 : Programming Languages

CSE 341 : Programming Languages Lecture 9 Lexical Scope, Closures Zach Tatlock Spring 2014 Very important concept We know function bodies can use any bindings in scope But now that functions can be passed

### CMSC 330, Fall 2013, Practice Problem 3 Solutions

CMSC 330, Fall 2013, Practice Problem 3 Solutions 1. OCaml and Functional Programming a. Define functional programming Programs are expression evaluations b. Define imperative programming Programs change

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

### Lectures Basics in Procedural Programming: Machinery

Lectures 3-4-5-6 Basics in Procedural Programming: Machinery February 21-28, 2014 2014-03-01 11:04:07 1/48 Lecture3-6E-2014.pdf (#21) Basics in Procedural Programming: Machinery Naming and Binding Mutable

### CSE 341: Programming Languages

CSE 341: Programming Languages Dan Grossman Spring 2008 Lecture 6 Nested pattern-matching; course motivation Dan Grossman CSE341 Spring 2008, Lecture 6 1 Patterns What we know: case-expresssions do pattern-matching

### CSCI-GA Scripting Languages

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

### INF 212 ANALYSIS OF PROG. LANGS FUNCTION COMPOSITION. Instructors: Crista Lopes Copyright Instructors.

INF 212 ANALYSIS OF PROG. LANGS FUNCTION COMPOSITION Instructors: Crista Lopes Copyright Instructors. Topics Recursion Higher-order functions Continuation-Passing Style Monads (take 1) Identity Monad Maybe

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

### Types and Type Inference

Types and Type Inference Mooly Sagiv Slides by Kathleen Fisher and John Mitchell Reading: Concepts in Programming Languages, Revised Chapter 6 - handout on the course homepage Outline General discussion

### CS558 Programming Languages

CS558 Programming Languages Fall 2017 Lecture 3a Andrew Tolmach Portland State University 1994-2017 Binding, Scope, Storage Part of being a high-level language is letting the programmer name things: variables

### Control in Sequential Languages

CS 242 2012 Control in Sequential Languages Reading: Chapter 8, Sections 8.1 8.3 (only) Section 7.3 of The Haskell 98 Report, Exception Handling in the I/O Monad, http://www.haskell.org/onlinelibrary/io-13.html

### CSCE 314 Programming Languages. Type System

CSCE 314 Programming Languages Type System Dr. Hyunyoung Lee 1 Names Names refer to different kinds of entities in programs, such as variables, functions, classes, templates, modules,.... Names can be

### Introduction to ML. Mooly Sagiv. Cornell CS 3110 Data Structures and Functional Programming

Introduction to ML Mooly Sagiv Cornell CS 3110 Data Structures and Functional Programming Typed Lambda Calculus Chapter 9 Benjamin Pierce Types and Programming Languages Call-by-value Operational Semantics

### To figure this out we need a more precise understanding of how ML works

Announcements: What are the following numbers: 74/2/70/17 (2:30,2:30,3:35,7:30) PS2 due Thursday 9/20 11:59PM Guest lecture on Tuesday 9/25 o No RDZ office hours next Friday, I am on travel A brief comment

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

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

### CS 360 Programming Languages Interpreters

CS 360 Programming Languages Interpreters Implementing PLs Most of the course is learning fundamental concepts for using and understanding PLs. Syntax vs. semantics vs. idioms. Powerful constructs like

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

### Introduction to OCaml

Fall 2018 Introduction to OCaml Yu Zhang Course web site: http://staff.ustc.edu.cn/~yuzhang/tpl References Learn X in Y Minutes Ocaml Real World OCaml Cornell CS 3110 Spring 2018 Data Structures and Functional

### Chapter 11 :: Functional Languages

Chapter 11 :: Functional Languages Programming Language Pragmatics Michael L. Scott Copyright 2016 Elsevier 1 Chapter11_Functional_Languages_4e - Tue November 21, 2017 Historical Origins The imperative

### Static Semantics. Winter /3/ Hal Perkins & UW CSE I-1

CSE 401 Compilers Static Semantics Hal Perkins Winter 2009 2/3/2009 2002-09 Hal Perkins & UW CSE I-1 Agenda Static semantics Types Symbol tables General ideas for now; details later for MiniJava project

### Types and Type Inference

CS 242 2012 Types and Type Inference Notes modified from John Mitchell and Kathleen Fisher Reading: Concepts in Programming Languages, Revised Chapter 6 - handout on Web!! Outline General discussion of

### Semantic Analysis. Outline. The role of semantic analysis in a compiler. Scope. Types. Where we are. The Compiler so far

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 Statically vs. Dynamically typed languages

### Compiler construction

Compiler construction Martin Steffen March 13, 2017 Contents 1 Abstract 1 1.1 Symbol tables. 1 1.1.1 Introduction 1 1.1.2 Symbol table design and interface.. 2 1.1.3 Implementing symbol tables 3 1.1.4

### CMSC 330, Fall 2013, Practice Problems 3

CMSC 330, Fall 2013, Practice Problems 3 1. OCaml and Functional Programming a. Define functional programming b. Define imperative programming c. Define higher-order functions d. Describe the relationship

### CSE413: Programming Languages and Implementation Racket structs Implementing languages with interpreters Implementing closures

CSE413: Programming Languages and Implementation Racket structs Implementing languages with interpreters Implementing closures Dan Grossman Fall 2014 Hi! I m not Hal J I love this stuff and have taught

### Introduction to ML. Mooly Sagiv. Cornell CS 3110 Data Structures and Functional Programming

Introduction to ML Mooly Sagiv Cornell CS 3110 Data Structures and Functional Programming The ML Programming Language General purpose programming language designed by Robin Milner in 1970 Meta Language

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

### CSE341: Programming Languages Lecture 9 Function-Closure Idioms. Dan Grossman Winter 2013

CSE341: Programming Languages Lecture 9 Function-Closure Idioms Dan Grossman Winter 2013 More idioms We know the rule for lexical scope and function closures Now what is it good for A partial but wide-ranging

### Introduction to ML. Mooly Sagiv. Cornell CS 3110 Data Structures and Functional Programming

Introduction to ML Mooly Sagiv Cornell CS 3110 Data Structures and Functional Programming The ML Programming Language General purpose programming language designed by Robin Milner in 1970 Meta Language

### Formal Semantics. Prof. Clarkson Fall Today s music: Down to Earth by Peter Gabriel from the WALL-E soundtrack

Formal Semantics Prof. Clarkson Fall 2015 Today s music: Down to Earth by Peter Gabriel from the WALL-E soundtrack Review Previously in 3110: simple interpreter for expression language: abstract syntax

### Informal Semantics of Data. semantic specification names (identifiers) attributes binding declarations scope rules visibility

Informal Semantics of Data semantic specification names (identifiers) attributes binding declarations scope rules visibility 1 Ways to Specify Semantics Standards Documents (Language Definition) Language

### CS 314 Principles of Programming Languages

CS 314 Principles of Programming Languages Lecture 15: Review and Functional Programming Zheng (Eddy) Zhang Rutgers University March 19, 2018 Class Information Midterm exam forum open in Sakai. HW4 and

### CIS24 Project #3. Student Name: Chun Chung Cheung Course Section: SA Date: 4/28/2003 Professor: Kopec. Subject: Functional Programming Language (ML)

CIS24 Project #3 Student Name: Chun Chung Cheung Course Section: SA Date: 4/28/2003 Professor: Kopec Subject: Functional Programming Language (ML) 1 Introduction ML Programming Language Functional programming

### Lecture 13 CIS 341: COMPILERS

Lecture 13 CIS 341: COMPILERS Announcements HW4: OAT v. 1.0 Parsing & basic code generation Due: March 28 th START EARLY! Midterm Exam Grades Available on Gradescope Zdancewic CIS 341: Compilers 2 Midterm

### Compilers. Type checking. Yannis Smaragdakis, U. Athens (original slides by Sam

Compilers Type checking Yannis Smaragdakis, U. Athens (original slides by Sam Guyer@Tufts) Summary of parsing Parsing A solid foundation: context-free grammars A simple parser: LL(1) A more powerful parser:

### G Programming Languages - Fall 2012

G22.2110-003 Programming Languages - Fall 2012 Lecture 4 Thomas Wies New York University Review Last week Control Structures Selection Loops Adding Invariants Outline Subprograms Calling Sequences Parameter

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

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

### CS 242. Fundamentals. Reading: See last slide

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

### G Programming Languages - Fall 2012

G22.2110-003 Programming Languages - Fall 2012 Lecture 3 Thomas Wies New York University Review Last week Names and Bindings Lifetimes and Allocation Garbage Collection Scope Outline Control Flow Sequencing

### Outline. Introduction Concepts and terminology The case for static typing. Implementing a static type system Basic typing relations Adding context

Types 1 / 15 Outline Introduction Concepts and terminology The case for static typing Implementing a static type system Basic typing relations Adding context 2 / 15 Types and type errors Type: a set of

### CMSC 330: Organization of Programming Languages. OCaml Imperative Programming

CMSC 330: Organization of Programming Languages OCaml Imperative Programming CMSC330 Fall 2017 1 So Far, Only Functional Programming We haven t given you any way so far to change something in memory All

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

### Robot Programming with Lisp

4. Functional Programming: Higher-order Functions, Map/Reduce, Lexical Scope Institute for Artificial University of Bremen 9 of November, 2017 Functional Programming Pure functional programming concepts

### Seminar in Programming Languages

Seminar in Programming Languages Shuly Wintner Fall 2010-11 Course web site: http://cs.haifa.ac.il/~shuly/teaching/10/plseminar/ Course Goals Programming Language Concepts A language is a conceptual universe

### CS 330 Lecture 18. Symbol table. C scope rules. Declarations. Chapter 5 Louden Outline

CS 0 Lecture 8 Chapter 5 Louden Outline The symbol table Static scoping vs dynamic scoping Symbol table Dictionary associates names to attributes In general: hash tables, tree and lists (assignment ) can

### CVO103: Programming Languages. Lecture 5 Design and Implementation of PLs (1) Expressions

CVO103: Programming Languages Lecture 5 Design and Implementation of PLs (1) Expressions Hakjoo Oh 2018 Spring Hakjoo Oh CVO103 2018 Spring, Lecture 5 April 3, 2018 1 / 23 Plan Part 1 (Preliminaries):

### G Programming Languages Spring 2010 Lecture 4. Robert Grimm, New York University

G22.2110-001 Programming Languages Spring 2010 Lecture 4 Robert Grimm, New York University 1 Review Last week Control Structures Selection Loops 2 Outline Subprograms Calling Sequences Parameter Passing

### CMSC 330: Organization of Programming Languages. Functional Programming with Lists

CMSC 330: Organization of Programming Languages Functional Programming with Lists CMSC330 Spring 2018 1 Lists in OCaml The basic data structure in OCaml Lists can be of arbitrary length Implemented as

### CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find

CS1622 Lecture 15 Semantic Analysis CS 1622 Lecture 15 1 Semantic Analysis How to build symbol tables How to use them to find multiply-declared and undeclared variables. How to perform type checking CS

### 1. true / false By a compiler we mean a program that translates to code that will run natively on some machine.

1. true / false By a compiler we mean a program that translates to code that will run natively on some machine. 2. true / false ML can be compiled. 3. true / false FORTRAN can reasonably be considered

### CS 314 Principles of Programming Languages. Lecture 13

CS 314 Principles of Programming Languages Lecture 13 Zheng Zhang Department of Computer Science Rutgers University Wednesday 19 th October, 2016 Zheng Zhang 1 CS@Rutgers University Class Information Reminder:

### Chapter 13: Reference. Why reference Typing Evaluation Store Typings Safety Notes

Chapter 13: Reference Why reference Typing Evaluation Store Typings Safety Notes References Computational Effects Also known as side effects. A function or expression is said to have a side effect if,

### Syntax Errors; Static Semantics

Dealing with Syntax Errors Syntax Errors; Static Semantics Lecture 14 (from notes by R. Bodik) One purpose of the parser is to filter out errors that show up in parsing Later stages should not have to

### CMSC 330: Organization of Programming Languages. Operational Semantics

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

### Static Semantics. Lecture 15. (Notes by P. N. Hilfinger and R. Bodik) 2/29/08 Prof. Hilfinger, CS164 Lecture 15 1

Static Semantics Lecture 15 (Notes by P. N. Hilfinger and R. Bodik) 2/29/08 Prof. Hilfinger, CS164 Lecture 15 1 Current Status Lexical analysis Produces tokens Detects & eliminates illegal tokens Parsing

### Lambda Calculus LC-1

Lambda Calculus LC-1 λ- Calculus History-1 Developed by Alonzo Church during 1930 s-40 s One fundamental goal was to describe what can be computed. Full definition of λ-calculus is equivalent in power

### INF 102 CONCEPTS OF PROG. LANGS FUNCTIONAL COMPOSITION. Instructors: James Jones Copyright Instructors.

INF 102 CONCEPTS OF PROG. LANGS FUNCTIONAL COMPOSITION Instructors: James Jones Copyright Instructors. Topics Recursion Higher-order functions Continuation-Passing Style Monads (take 1) Identity Monad

### Programming Languages Third Edition. Chapter 10 Control II Procedures and Environments

Programming Languages Third Edition Chapter 10 Control II Procedures and Environments Objectives Understand the nature of procedure definition and activation Understand procedure semantics Learn parameter-passing

### Equivalent Notations. Higher-Order Functions. (define (f x y) ( body )) = (define f (lambda (x y) ) ) Anonymous Functions.

Equivalent Notations Higher-Order Functions cs480 (Prasad L156HOF 1 (define (f x y ( body = (define f (lambda (x y ( body cs480 (Prasad L156HOF 2 Function Values (define tag (lambda (t l (cons t l (tag

### CSE3322 Programming Languages and Implementation

Monash University School of Computer Science & Software Engineering Exam 2005 CSE3322 Programming Languages and Implementation Total Time Allowed: 3 Hours 1. Reading time is of 10 minutes duration. 2.

### CMSC 330: Organization of Programming Languages. Functional Programming with Lists

CMSC 330: Organization of Programming Languages Functional Programming with Lists 1 Lists in OCaml The basic data structure in OCaml Lists can be of arbitrary length Implemented as a linked data structure

### Lambda Calculus. Gunnar Gotshalks LC-1

Lambda Calculus LC-1 l- Calculus History Developed by Alonzo Church during 1930 s-40 s One fundamental goal was to describe what can be computed. Full definition of l-calculus is equivalent in power to

### News. CSE 130: Programming Languages. Environments & Closures. Functions are first-class values. Recap: Functions as first-class values

CSE 130: Programming Languages Environments & Closures News PA 3 due THIS Friday (5/1) Midterm NEXT Friday (5/8) Ranjit Jhala UC San Diego Recap: Functions as first-class values Arguments, return values,

### CSE 307: Principles of Programming Languages

1 / 26 CSE 307: Principles of Programming Languages Names, Scopes, and Bindings R. Sekar 2 / 26 Topics Bindings 1. Bindings Bindings: Names and Attributes Names are a fundamental abstraction in languages

### Functional Languages. CSE 307 Principles of Programming Languages Stony Brook University

Functional Languages CSE 307 Principles of Programming Languages Stony Brook University http://www.cs.stonybrook.edu/~cse307 1 Historical Origins 2 The imperative and functional models grew out of work

### OCaml Data CMSC 330: Organization of Programming Languages. User Defined Types. Variation: Shapes in Java

OCaml Data : Organization of Programming Languages OCaml 4 Data Types & Modules So far, we ve seen the following kinds of data Basic types (int, float, char, string) Lists Ø One kind of data structure

### Functional Programming

The Meta Language (ML) and Functional Programming Daniel S. Fava danielsf@ifi.uio.no Department of informatics University of Oslo, Norway Motivation ML Demo Which programming languages are functional?

### CS 415 Midterm Exam Spring 2002

CS 415 Midterm Exam Spring 2002 Name KEY Email Address Student ID # Pledge: This exam is closed note, closed book. Good Luck! Score Fortran Algol 60 Compilation Names, Bindings, Scope Functional Programming

### Harvard School of Engineering and Applied Sciences CS 152: Programming Languages

Harvard School of Engineering and Applied Sciences CS 152: Programming Languages Lecture 24 Thursday, April 19, 2018 1 Error-propagating semantics For the last few weeks, we have been studying type systems.

### CMSC 330: Organization of Programming Languages. OCaml Imperative Programming

CMSC 330: Organization of Programming Languages OCaml Imperative Programming CMSC330 Spring 2018 1 So Far, Only Functional Programming We haven t given you any way so far to change something in memory