Control in Sequential Languages
|
|
- Brianna Dean
- 5 years ago
- Views:
Transcription
1 Control in Sequential Languages Structured Programming Go to considered harmful Exceptions structured jumps that may return a value dynamic scoping of exception handler Continuations Function representing the rest of the program Generalized form of tail recursion Functions and evaluation order Control evaluation order using function definitions and calls L. Dillon, CSE 452, Fall
2 Idea: The continuation of an expression is the remaining work to be done after evaluating the expression Continuation of expression General programming technique e is a function; normally applied to e Capture the continuation at some point in a program Use it later: jump or exit by function call Useful in Compiler optimization: make control flow explicit Operating system scheduling, multiprogramming Web programming Continuations L. Dillon, CSE 452, Fall
3 Example: Roots of a quadratic equation Version 0: without any continuations exception notquadratic; exception imaginaryroots; fun equal(x:real, y:real) = x <= y andalso x >= y; fun roots(a, b, c) = let val discbase = (b*b) - (4.0*a*c) val denom = 2.0*a in if equal(denom, 0.0) then raise notquadratic else if discbase < 0.0 then raise imaginaryroots else let val disc = Math.sqrt(discBase) in if disc > 0.0 then [(~b + disc)/denom, (~b - disc)/denom] else [~b/denom] end end; L. Dillon, CSE 452, Fall
4 Example: Roots of a quadratic equation Version 1: Uses a normal continuation and an error continuation fun checkquad (x, n_continuation, e_continuation) = if equal(x, 0.0) then e_continuation() else n_continuation(x); fun roots1(a, b, c) = let fun econt () = raise notquadratic fun ncont (x) = let val discbase = (b*b) - (4.0*a*c) in if discbase < 0.0 then raise imaginaryroots else let val disc = Math.sqrt(discBase) in if disc>0.0 then [(~b + disc)/x, (~b - disc)/x] else [~b/x] end end in checkquad(2.0*a, ncont, econt) end; L. Dillon, CSE 452, Fall
5 Example: Roots of a quadratic equation Version 2: Like version 1, uses normal and error continuations fun checkimaginary (x, n_continuation, e_continuation) = if x < 0.0 then e_continuation() else n_continuation(math.sqrt(x)); fun roots2(a, b, c) = let fun econt () = raise notquadratic fun ncont (x) = let fun econt () = raise imaginaryroots fun ncont (disc) = if disc > 0.0 then [(~b + disc)/x, (~b - disc)/x] else [~b/x] in checkimaginary(b*b - 4.0*a*c, ncont, econt) end in checkquad(2.0*a, ncont, econt) end; L. Dillon, CSE 452, Fall
6 Example: Roots of a quadratic equation Version 3: Uses continuations to calculate the roots fun checknumroots(disc, continuation1, continuation2) = if disc > 0.0 then continuation1(disc) else continuation2(); fun roots3(a, b, c) = let fun econt () = raise notquadratic fun ncont (x) = let fun econt () = raise imaginaryroots fun ncont (disc) = let fun con1 (disc) = [(~b + disc)/x, (~b - disc)/x] fun con2 () = [~b/x] in checknumroots(disc, con1, con2) end in checkimaginary(b*b - 4.0*a*c, ncont, econt) end in checkquad(2.0*a, ncont, econt) end; L. Dillon, CSE 452, Fall
7 Continuation-passing form (CPF) & tail recursion Standard definition: fun fac(n) = if n = 1 then 1 else n * fac(n-1); Tail-recursive version: fun fac(n) = let fun f(n,k) = if n = 0 then k else f(n-1, n*k) in f(n,1) end; Standard definition: fun digits(n) = if n < 10 then 1 else 1 + digits(n div 10); Tail-recursive version: fun digits(n) = let fun d(n,k) = if n < 10 then k else d(n div 10, 1 + k) in d(n,1) end; How could we derive these? Transform to continuation-passing form Optimize continuation functions to single integer (See Mitchell for derivation of the tail-recursive version of fac.) L. Dillon, CSE 452, Fall
8 Continuation-passing form (CPF) & tail recursion The CPF of a function f of n arguments is a function f cpf of n+1 arguments. The last argument to f cpf is a continuation, which is to be applied to the value returned by applying f to the first n arguments. That is: f cpf (x 1, x 2,..., x n, k) = k ( f (x 1, x 2,..., x n ) ) Observation: f cpf (x 1, x 2,..., x n, my.y) = my.y ( f (x 1, x 2,..., x n ) ) = f (x 1, x 2,..., x n ) L. Dillon, CSE 452, Fall
9 1. Example: Derivation of tail-recursive form Standard definition: fun digits(n) = if n < 10 then 1 else 1 + digits(n div 10); 2. To obtain the CPF, we need to define a function d satisfying: d(n,k) = k(digits(n)) 3. From 1 & 2 it follows that : a. if n < 10, we need: d(n,k) = k(digits(n)) = k(1) b. if n 10, we need: d(n,k) = k(digits(n)) = k(1 + digits(n div 10)) = mx.(k(1+x))(digits(n div 10)) = d(n div 10, mx.(k(1+x))) 4. This motivates the definition: d(n,k) = if n < 10 then k(1) else d(n div 10, mx.k(1+x)) L. Dillon, CSE 452, Fall
10 Given the function in CPF: Exercise d(n,k) = if n < 10 then k(1) else d(n div 10, mx.k(1+x)) Show the steps to calculate: d(235, my.y) = d(23, mx.(my.y(1+x))) = d(23, mz.(1+z)) = d(2, mx.(mz.(1+z)(1+x)) = d(2, mx.(1+(1+x))) = d(2, mx.(2+x)) = mx.(2+x)(1) = 3 L. Dillon, CSE 452, Fall
11 Exercise L. Dillon, CSE 452, Fall
12 Example: Derivation of tail-recursive form Want to optimize each continuation into an integer. For this, observe that during a calculation, Each continuation reduces to the form, Starts with mx.(a+x), for some a a = 0, and increases by 1 on each recursive application of d At the bottom of the recursion, get result by increasing a by 1 For example: d(2350,mx.x) = d(235,mx.(1+x)) = d(23,mx.(2+x)) = d(2,mx.(3+x)) = 4 This observation motivates the definitions: fun d(n,a) = if n<10 then a+1 else d(n div 10, a+1); fun digits(n) = d(n,0); Example calculation: d(2350,0) = d(235,1) = d(23,2) = d(2,3) = 4 L. Dillon, CSE 452, Fall
13 Capturing the current continuation Recall: The continuation of an expression e is an abstraction of what the system will do with the value of e e.g., continuation of x*x in sqrt(x*x+y*y) is mz.sqrt(z+y*y) SML/NJ provides a structure (library module) for capturing a continuation for later use (application): structure SMLofNJ.Cont : sig type a cont val callcc : ( a cont -> a) -> a val throw : a cont -> a -> b... end To use it: -open SMLofNJ.Cont; L. Dillon, CSE 452, Fall
14 type a cont Capturing the current continuation The type of continuations accepting arguments of type a callcc f Capture the current configuration, cc, and apply f to it; if f executes a throw instruction with cc and argument x, then callcc f returns x as a result; otherwise it returns the value returned by f. throw k a Throw continuation k with argument a Example: - val x = 3 : int callcc(fn k => if x > 0 then x + 1 else throw k ~1); - val x = 0 : int callcc(fn k => if x > 0 then x + 1 else throw k ~1); L. Dillon, CSE 452, Fall
15 Example 1 + callcc(fn k1 =>... callcc(fn k2 =>... if... then (throw k1 0) else (throw k2 stuck ) )) Intuition More with callcc Callcc lets you mark a point in program that you can return to Throw lets you jump to that point and continue from there L. Dillon, CSE 452, Fall
16 OS kernel schedules multiple threads Each thread may have a separate stack Stack of blocked thread is stored within the kernel Mach continuation approach Blocked thread represented as Pointer to a continuation function, list of arguments Stack is discarded when thread blocks Programming implications System call such as Kernel code calls Advantage/Disadvantage Saves Continuations in Mach OS msg_recv can block msg_recv with continuation passed as an argument a lot of space, need to write continuation functions L. Dillon, CSE 452, Fall
17 Continuations in web programming Asynchronous XHR similar to continuations: function callwithcontinuation(url, k) { var xhr = new XMLHttpRequest(); xhr.open( GET, url, true); xhr.onreadystatechange = function () { if (xhr.readystate == 4) k(xhr.responsetext); } xhr.send(null); } Usage: callwithcontinuation( alert); Client continues while server runs Basis of AJAX Web programming paradigm L. Dillon, CSE 452, Fall
18 Continuations in compilation SML continuation-based compiler [Appel, Steele] 1) Lexical analysis, parsing, type checking 2) Translation to m-calculus form 3) Conversion to continuation-passing style (CPS) 4) Optimization of CPS 5) Closure conversion eliminate free variables 6) Elimination of nested scopes 7) Register spilling no expression with more than n free vars 8) Generation of target assembly language program 9) Assemble to produce target-machine program L. Dillon, CSE 452, Fall
19 Functions and evaluation order Evaluation of ML expression is eager Call-by-value: evaluate args to a function before application Inefficient if the values of some arguments are not needed during evaluation of the function body Other evaluation strategies Call-by-reference: pass L-values of args to the function To access the value of a formal involves extra level of indirection Leads to aliasing, complications on abnormal termination, etc. Call-by-need: Pass function (closure) with which to compute the value of an arg, when/if it is needed called lazy evaluation Optimization: memoize an argument value when it is first used, avoid recalculating it on subsequent uses L. Dillon, CSE 452, Fall
20 Delay and Force (Version #1) Macros that implement call-by-need in a language with eager evaluation, static scoping and HO functions E.g., to pass x eagerly (by-value) and y lazily (by-need) - fun f(x, y) =... x... Force(y)... - f(e1, Delay(e2)); Implementing Delay and Force in ML Delay(e) == fn() => e Force(e) == e() Example exception NegVal of real; fun expensive(x) =... fun foo(x, y) = if x >= 0 then Math.pow(x,y()) else raise NegVal(x); foo(~1.0, fn()=>expensive(10.0)); foo(1.0, fn()=>expensive(10.0)); L. Dillon, CSE 452, Fall
21 How does it work? exception NegVal of real; a: fun expensive(x) =... fun foo(x, y) = b: if x >= 0 then Math.pow(x,y()) EP: else raise NegVal(x); foo(~1.0, c: fn()=>expensive(10.0)); foo(1.0, d: fn()=>expensive(10.0)); (foo(~1...) :PC AL: expensive: AL: foo: 2nd arg: AL: x: y: ~1.0 Rather than pass in the value of expensive(10.0), pass a closure that, if called, will evaluate expensive(10.0). c a b The call foo(~1.0...) does not invoke its second argument, so expensive(10.0) is not evaluated. L. Dillon, CSE 452, Fall
22 How does it work? exception NegVal of real; a: fun expensive(x) =... fun foo(x, y) = b: if x >= 0 then Math.pow(x,y()) EP: :PC else raise NegVal(x); foo(~1.0, c: fn()=>expensive(10.0)); foo(1.0, d: fn()=>expensive(10.0)); AL: expensive: (foo(1...) AL: foo: 2nd arg: AL: x: y: 1.0 Rather than pass in the value of expensive(10.0), pass a closure that, if called, will evaluate expensive(10.0). d a b The call foo(1.0...) calls... L. Dillon, CSE 452, Fall
23 How does it work? exception NegVal of real; a: fun expensive(x) =... fun foo(x, y) = b: if x >= 0 then Math.pow(x,y()) else raise NegVal(x); EP: foo(~1.0, c: fn()=>expensive(10.0)); foo(1.0, d: fn()=>expensive(10.0)); AL: expensive: (foo(1...) AL: foo: 2nd arg: (y()) AL: x: y: AL: (expens...) AL: 1.0 x: 10.0 Rather than pass in the value of expensive(10.0), pass a closure that, :PC if called, will evaluate expensive(10.0). d a b The call foo(1.0...) calls... y() which in turn calls... L. Dillon, CSE 452, Fall
24 How does it work? exception NegVal of real; a: fun expensive(x) =... fun foo(x, y) = b: if x >= 0 then Math.pow(x,y()) else raise NegVal(x); foo(~1.0, c: EP: fn()=>expensive(10.0)); foo(1.0, d: fn()=>expensive(10.0)); :PC AL: expensive: (foo(1...) AL: foo: 2nd arg: AL: x: y: AL: (expens...) AL: 1.0 x: 10.0 Rather than pass in the value of expensive(10.0), pass a closure that, if called, will evaluate expensive(10.0). d a b The call foo(1.0...) calls... y(), which in turn calls... expensive(10.0). L. Dillon, CSE 452, Fall
25 Delay and Force (Version #2) Suppose the delayed value is needed more than once in evaluating the function body. If the argument is pure (no side-effects), would like to avoid re-evaluating the argument: Represent argument using memoization (common design idiom) Flag: indicates if the argument has been evaluated previously or not datatype a delay = EV of a UN of unit -> a; Value: Initially, a parameter-less function (closure) that, when applied, returns the value of the actual argument; Delay(e) == ref(un(fn() => e) After the first time the argument is evaluated, the value of the argument fun ev(ev(x)) = x ev(un(f)) = f(); fun force(d) = let val v = ev(!d) in (d := EV(v); v) end; L. Dillon, CSE 452, Fall
26 How does it work? datatype a delay = EV of a UN of unit -> a; (lazy _...)... a (* ev: a delay -> a *) fun ev(ev(x)) = x ev(un(f)) = f(); (* force: a delay ref -> a *) fun force(d) = let val v = ev(!d) in (d := EV(v); v) end; (* lazy_poly: real delay ref * int -> real *) fun lazy_poly(x,n) = if n<1 then 1.0 else Math.pow(force(x),real(n)) + lazy_poly(x,n-1); EP: (* expensive: int -> real *) fun expensive(x) =... :PC a: lazy_poly(ref(un(fn() => expensive(7))), 3); x: n: 3 (force(x))... d: v: (ev(!d))... f: (f())... (expen...)... x: 7 UN (* assume: expensive(7) = 21.0 *) L. Dillon, CSE 452, Fall
27 How does it work? datatype a delay = EV of a UN of unit -> a; (* ev: a delay -> a *) fun ev(ev(x)) = x ev(un(f)) = f(); EP: (* force: a delay ref -> a *) fun force(d) = let val v = ev(!d) in (d := EV(v); v) end; (* lazy_poly: :PC real delay ref * int -> real *) fun lazy_poly(x,n) = if n<1 then 1.0 else Math.pow(force(x),real(n)) + lazy_poly(x,n-1); (* expensive: int -> real *) fun expensive(x) =... a: lazy_poly(ref(un(fn() => expensive(7))), 3); (lazy _...)... x: n: 3 (force(x))... d: v: (ev(!d))... f: 21.0 (f())... (expen...)... x: 7 a UN EV 21. (* assume: expensive(7) = 21.0 *) L. Dillon, CSE 452, Fall
28 How does it work? datatype a delay = EV of a UN of unit -> a; (* ev: a delay -> a *) fun ev(ev(x)) = x ev(un(f)) = f(); :PC (* force: a delay ref -> a *) fun force(d) = let val v = ev(!d) in (d := EV(v); v) end; (* lazy_poly: real delay ref * int -> real *) fun lazy_poly(x,n) = if n<1 then 1.0 else Math.pow(force(x),real(n)) + EP: lazy_poly(x,n-1); (* expensive: int -> real *) fun expensive(x) =... a: lazy_poly(ref(un(fn() => expensive(7))), 3); (lazy _...)... x: n: 3 (force(x)) (lazy _...).... d: x: v: n: 2 (ev(!d)) (force(x)).... d: f: (f()) v:... (ev(!d))... (expen...).. x: 21.. x: 7 a UN EV 21. (* assume: expensive(7) = 21.0 *) L. Dillon, CSE 452, Fall
29 Structured Programming Go to considered harmful Exceptions structured jumps that may return a value dynamic scoping of exception handler Continuations Function representing the rest of the program Generalized form of tail recursion Used in Lisp and ML compilation, some OS projects, web application development, Delay and force Summary Used to delay a computation until it is needed L. Dillon, CSE 452, Fall
Iterators. Lecture 24: Iterators & Exceptions. Implementing Iterators. When Good Programs Go Bad! - where! Abstract over control structures (in Clu)!
Iterators Lecture 24: Iterators & Exceptions CSC 131 Fall, 2014 Kim Bruce Abstract over control structures (in Clu) - where for c : char in string_chars(s) do string_chars = iter (s : string) yields (char);
More informationControl 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
More informationContinuations and Continuation-Passing Style
Continuations and Continuation-Passing Style Lecture 4 CS 390 1/16/08 Goal Weʼre interested in understanding how to represent the state of a co-routine Insight into what a thread really means How fundamental
More informationScope, 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)
More informationClosures. 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 Summary 1. Predictive Parsing 2. Large Step Operational Semantics (Natural) 3. Small Step Operational Semantics
More informationCSE 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
More informationThreads and Continuations COS 320, David Walker
Threads and Continuations COS 320, David Walker Concurrency Concurrency primitives are an important part of modern programming languages. Concurrency primitives allow programmers to avoid having to specify
More informationBegin 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
More informationCS 312. Lecture April Lazy Evaluation, Thunks, and Streams. Evaluation
CS 312 Lecture 27 29 April 2008 Lazy Evaluation, Thunks, and Streams Evaluation SML as you know it (substitution semantics) if true then e 1 else e 2 e 1 if false then e 1 else e 2 e 2 if eagerly evaluates
More informationClosures. 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.
More informationCSE341: 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
More informationDesign 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
More informationRun-time Environments
Run-time Environments Status We have so far covered the front-end phases Lexical analysis Parsing Semantic analysis Next come the back-end phases Code generation Optimization Register allocation Instruction
More informationRun-time Environments
Run-time Environments Status We have so far covered the front-end phases Lexical analysis Parsing Semantic analysis Next come the back-end phases Code generation Optimization Register allocation Instruction
More informationCSE341: Programming Languages Lecture 9 Function-Closure Idioms. Dan Grossman Fall 2011
CSE341: Programming Languages Lecture 9 Function-Closure Idioms Dan Grossman Fall 2011 More idioms We know the rule for lexical scope and function closures Now what is it good for A partial but wide-ranging
More informationAnnouncements. 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
More informationCSE341: Programming Languages Lecture 17 Implementing Languages Including Closures. Dan Grossman Autumn 2018
CSE341: Programming Languages Lecture 17 Implementing Languages Including Closures Dan Grossman Autumn 2018 Typical workflow concrete syntax (string) "(fn x => x + x) 4" Parsing Possible errors / warnings
More informationTypical Runtime Layout. Tiger Runtime Environments. Example: Nested Functions. Activation Trees. code. Memory Layout
Tiger Runtime Environments Compile-time environments are just symbol tables; they are used to assist static semantic analysis, code generation and code optimization. Run-time environments are about how
More informationTail 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,
More informationWeeks 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
More informationVariables 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
More informationKonzepte von Programmiersprachen
Konzepte von Programmiersprachen Chapter 5: Continuation-Passing Interpreters Stefan Wehr Universität Freiburg 8. Juni 2009 Konzepte von Programmiersprachen 1 / 43 Motivation Continuations: abstraction
More informationFunctional programming techniques
Functional programming techniques o Currying o Continuations o Streams. Lazy evaluation Currying o Haskell B. Curry. o Second-order programming: o Functions that return other functions. o Example: A two-arguments
More informationCS 345. Exceptions. Vitaly Shmatikov. slide 1
CS 345 Exceptions Vitaly Shmatikov slide 1 Reading Assignment Mitchell, Chapter 8.2 slide 2 Exceptions: Structured Exit Terminate part of computation Jump out of construct Pass data as part of jump Return
More informationConcepts Introduced in Chapter 7
Concepts Introduced in Chapter 7 Storage Allocation Strategies Static Stack Heap Activation Records Access to Nonlocal Names Access links followed by Fig. 7.1 EECS 665 Compiler Construction 1 Activation
More informationCOP4020 Programming Assignment 1 - Spring 2011
COP4020 Programming Assignment 1 - Spring 2011 In this programming assignment we design and implement a small imperative programming language Micro-PL. To execute Mirco-PL code we translate the code to
More informationFall 2018 Lecture N
15-150 Fall 2018 Lecture N Tuesday, 20 November I m too lazy to figure out the correct number Stephen Brookes midterm2 Mean: 79.5 Std Dev: 18.4 Median: 84 today or, we could procrastinate lazy functional
More informationThe 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
More informationLecture 09: Data Abstraction ++ Parsing is the process of translating a sequence of characters (a string) into an abstract syntax tree.
Lecture 09: Data Abstraction ++ Parsing Parsing is the process of translating a sequence of characters (a string) into an abstract syntax tree. program text Parser AST Processor Compilers (and some interpreters)
More informationReferences and Exceptions. CS 565 Lecture 14 4/1/08
References and Exceptions CS 565 Lecture 14 4/1/08 References In most languages, variables are mutable: it serves as a name for a location the contents of the location can be overwritten, and still be
More informationSemantic 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
More informationSide 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,
More informationProgramming Languages and Compilers (CS 421)
Programming Languages and Compilers (CS 421) Elsa L Gunter 2112 SC, UIUC http://courses.engr.illinois.edu/cs421 Based in part on slides by Mattox Beckman, as updated by Vikram Adve and Gul Agha 9/18/17
More informationG 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
More informationCSE3322 Programming Languages and Implementation
Monash University School of Computer Science & Software Engineering Sample Exam 2004 CSE3322 Programming Languages and Implementation Total Time Allowed: 3 Hours 1. Reading time is of 10 minutes duration.
More informationn What is its running time? 9/18/17 2 n poor_rev [1,2,3] = n (poor_rev [1] = n ((poor_rev [1] =
Recall Programming Languages and Compilers (CS 421) Elsa L Gunter 2112 SC, UIUC http://courses.engr.illinois.edu/cs421 Based in part on slides by Mattox Beckman, as updated by Vikram Adve and Gul Agha
More informationCS558 Programming Languages
CS558 Programming Languages Winter 2017 Lecture 7b Andrew Tolmach Portland State University 1994-2017 Values and Types We divide the universe of values according to types A type is a set of values and
More informationAn 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
More informationUNIT 3
UNIT 3 Presentation Outline Sequence control with expressions Conditional Statements, Loops Exception Handling Subprogram definition and activation Simple and Recursive Subprogram Subprogram Environment
More informationCS153: Compilers Lecture 15: Local Optimization
CS153: Compilers Lecture 15: Local Optimization Stephen Chong https://www.seas.harvard.edu/courses/cs153 Announcements Project 4 out Due Thursday Oct 25 (2 days) Project 5 out Due Tuesday Nov 13 (21 days)
More informationFunctional 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
More informationG 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
More informationThe 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
More informationCPS Conversion. Di Zhao.
CPS Conversion Di Zhao zhaodi01@mail.ustc.edu.cn This is the first assignment of the course - Advanced Topics in Software Technologies in the 2014-2015 academic year. During this course, we will explore
More informationCS558 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.
More informationSemantic 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
More informationCS 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
More informationCMSC330. Objects, Functional Programming, and lambda calculus
CMSC330 Objects, Functional Programming, and lambda calculus 1 OOP vs. FP Object-oriented programming (OOP) Computation as interactions between objects Objects encapsulate mutable data (state) Accessed
More information4.5 Pure Linear Functional Programming
4.5 Pure Linear Functional Programming 99 4.5 Pure Linear Functional Programming The linear λ-calculus developed in the preceding sections can serve as the basis for a programming language. The step from
More informationProgramming 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
More informationDO 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
More informationINF 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
More informationCSE 341: Programming Languages
CSE 341: Programming Languages Winter 2005 Lecture 17 varargs and apply, implementing higher-order functions CSE341 Winter 2005, Lecture 17 1 Today: Some easy Scheme odds and ends Implementing higher-order
More informationCS 345. Functions. Vitaly Shmatikov. slide 1
CS 345 Functions Vitaly Shmatikov slide 1 Reading Assignment Mitchell, Chapter 7 C Reference Manual, Chapters 4 and 9 slide 2 Procedural Abstraction Can be overloaded (e.g., binary +) Procedure is a named
More informationUNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division
UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division Fall, 2001 Prof. R. Fateman SUGGESTED S CS 164 Final Examination: December 18, 2001, 8-11AM
More informationThe Compiler So Far. Lexical analysis Detects inputs with illegal tokens. Overview of Semantic Analysis
The Compiler So Far Overview of Semantic Analysis Adapted from Lectures by Profs. Alex Aiken and George Necula (UCB) Lexical analysis Detects inputs with illegal tokens Parsing Detects inputs with ill-formed
More informationProject Compiler. CS031 TA Help Session November 28, 2011
Project Compiler CS031 TA Help Session November 28, 2011 Motivation Generally, it s easier to program in higher-level languages than in assembly. Our goal is to automate the conversion from a higher-level
More informationCOP4020 Programming Languages. Functional Programming Prof. Robert van Engelen
COP4020 Programming Languages Functional Programming Prof. Robert van Engelen Overview What is functional programming? Historical origins of functional programming Functional programming today Concepts
More informationTest 1 Summer 2014 Multiple Choice. Write your answer to the LEFT of each problem. 5 points each 1. Preprocessor macros are associated with: A. C B.
CSE 3302 Test 1 1. Preprocessor macros are associated with: A. C B. Java C. JavaScript D. Pascal 2. (define x (lambda (y z) (+ y z))) is an example of: A. Applying an anonymous function B. Defining a function
More informationCSE341: Programming Languages Lecture 6 Nested Patterns Exceptions Tail Recursion. Zach Tatlock Winter 2018
CSE341: Programming Languages Lecture 6 Nested Patterns Exceptions Tail Recursion Zach Tatlock Winter 2018 Nested patterns We can nest patterns as deep as we want Just like we can nest expressions as deep
More informationCSE341 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
More informationVerification 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
More informationCSE413: 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
More informationCSE 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
More informationINF 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
More informationCS 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
More informationProcessadors 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
More informationCIS24 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
More informationRecursion. Tjark Weber. Functional Programming 1. Based on notes by Sven-Olof Nyström. Tjark Weber (UU) Recursion 1 / 37
Tjark Weber Functional Programming 1 Based on notes by Sven-Olof Nyström Tjark Weber (UU) Recursion 1 / 37 Background FP I / Advanced FP FP I / Advanced FP This course (Functional Programming I) (5 hp,
More informationCSE 413 Midterm, May 6, 2011 Sample Solution Page 1 of 8
Question 1. (12 points) For each of the following, what value is printed? (Assume that each group of statements is executed independently in a newly reset Scheme environment.) (a) (define x 1) (define
More informationCHAPTER ONE OVERVIEW. 1.1 Continuation-passing style
CHAPTER ONE OVERVIEW ML is a strict higher-order functional programming language with statically checked polymorphic types, garbage collection, and a complete formally defined semantics. Standard ML of
More informationThe 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
More informationCSE 341: Programming Languages
CSE 341: Programming Languages Autumn 2005 Lecture 10 Mutual Recursion, Equivalence, and Syntactic Sugar CSE 341 Autumn 2005, Lecture 10 1 Mutual Recursion You ve already seen how multiple functions can
More informationAssigning to a Variable
What is the result of this program? Is it 0 or 1? Assigning to a Variable let f = proc(x) set x = 1 in let y = 0 in { (f y); y } 1 Assigning to a Variable let f = proc(x) set x = 1 in let y = 0 in { (f
More information15 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
More informationCS558 Programming Languages Winter 2018 Lecture 4a. Andrew Tolmach Portland State University
CS558 Programming Languages Winter 2018 Lecture 4a Andrew Tolmach Portland State University 1994-2018 Pragmatics of Large Values Real machines are very efficient at handling word-size chunks of data (e.g.
More informationCSE3322 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.
More informationFunctional Languages. Hwansoo Han
Functional Languages Hwansoo Han Historical Origins Imperative and functional models Alan Turing, Alonzo Church, Stephen Kleene, Emil Post, etc. ~1930s Different formalizations of the notion of an algorithm
More informationCSE341 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
More informationCSci 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
More informationPrograms as data first-order functional language type checking
Programs as data first-order functional language type checking Copyright 2013-18, Peter Sestoft and Cesare Tinelli. Created by Cesare Tinelli at the University of Iowa from notes originally developed by
More informationLists. 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
More informationPolymorphism and Type Inference
Polymorphism and Type Inference Volker Stolz stolz@ifi.uio.no Department of Informatics University of Oslo Initially by Gerardo Schneider. Based on John C. Mitchell s slides (Stanford U.) Compile-time
More informationNews. 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
More informationParsing Scheme (+ (* 2 3) 1) * 1
Parsing Scheme + (+ (* 2 3) 1) * 1 2 3 Compiling Scheme frame + frame halt * 1 3 2 3 2 refer 1 apply * refer apply + Compiling Scheme make-return START make-test make-close make-assign make- pair? yes
More informationFunctional 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
More informationFirst-class continuations. call/cc, stack-passing CEK machines
First-class continuations call/cc, stack-passing CEK machines But first Assignment 2 e ::= (letrec* ([x e]...) e) (letrec ([x e]...) e) (let* ([x e]...) e) (let ([x e]...) e) (let x ([x e]...) e) (lambda
More informationChapter 7 Control I Expressions and Statements
Chapter 7 Control I Expressions and Statements Expressions Conditional Statements and Guards Loops and Variation on WHILE The GOTO Controversy Exception Handling Values and Effects Important Concepts in
More informationTypical workflow. CSE341: Programming Languages. Lecture 17 Implementing Languages Including Closures. Reality more complicated
Typical workflow concrete synta (string) "(fn => + ) 4" Parsing CSE341: Programming Languages abstract synta (tree) Lecture 17 Implementing Languages Including Closures Function Constant + 4 Var Var Type
More informationProgramming 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
More informationCSE341 Autumn 2017, Midterm Examination October 30, 2017
CSE341 Autumn 2017, Midterm Examination October 30, 2017 Please do not turn the page until 2:30. Rules: The exam is closed-book, closed-note, etc. except for one side of one 8.5x11in piece of paper. Please
More informationCS 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
More informationG 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
More informationSample Exam; Solutions
Sample Exam; Solutions Michael P. Fourman February 2, 2010 1 Introduction This document contains solutions to the sample questions given in Lecture Note 10 Short Question 5 marks Give the responses of
More informationTopic IV. Parameters. Chapter 5 of Programming languages: Concepts & constructs by R. Sethi (2ND EDITION). Addison-Wesley, 1996.
References: Topic IV Block-structured procedural languages Algol and Pascal Chapters 5 and 7, of Concepts in programming languages by J. C. Mitchell. CUP, 2003. Chapter 5 of Programming languages: Concepts
More informationCSE 341 : Programming Languages Midterm, Spring 2015
Name: CSE 341 : Programming Languages Midterm, Spring 2015 Please do not turn the page until 12:30. Rules: Closed book, closed note, except for one side of one 8.5x11in piece of paper. Please stop promptly
More informationContinuation Passing Style. Continuation Passing Style
161 162 Agenda functional programming recap problem: regular expression matcher continuation passing style (CPS) movie regular expression matcher based on CPS correctness proof, verification change of
More informationHomework 5. Notes. Turn-In Instructions. Reading. Problems. Handout 19 CSCI 334: Spring (Required) Read Mitchell, Chapters 6 and 7.
Homework 5 Due Wednesday, 14 March Handout 19 CSCI 334: Spring 2018 Notes This homework has two types of problems: Problems: You will turn in answers to these questions. Pair Programming: This part involves
More informationlow and not larger than high. 18 points
CSE 330 Test 1 (1 point) Spring 015 Multiple Choice. Write your answer to the LEFT of each problem. 3 points each 1. Lisp was invented at: A. IBM B. MIT C. Netscape D. Stanford. In C++, what operator is
More information4 Functional Programming Languages
4 Functional Programming Languages What is a function? The mathematical notion : if f(x) = a this time, then f(x) = a next time ; there is no other value equal to f(x) Ex (equational reasoning) : if a
More information