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

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

Scope, Functions, and Storage Management

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

Control in Sequential Languages

Continuations and Continuation-Passing Style

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

Topic 7: Activation Records

Parsing Scheme (+ (* 2 3) 1) * 1

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

Recap: Functions as first-class values

INF3110 Programming Languages Runtime Organization part II

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

The role of semantic analysis in a compiler

Variables and Bindings

CS558 Programming Languages

Chapter 5. Names, Bindings, and Scopes

CS558 Programming Languages

INF 212 ANALYSIS OF PROG. LANGS ELEMENTS OF IMPERATIVE PROGRAMMING STYLE. Instructors: Crista Lopes Copyright Instructors.

CMSC 330: Organization of Programming Languages

Chapter 1. Fundamentals of Higher Order Programming

Short Notes of CS201

INF3110 Programming Languages Runtime Organization part II

CS201 - Introduction to Programming Glossary By

Compilers: The goal. Safe. e : ASM

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

Compiler Construction Lent Term 2015 Lectures 10, 11 (of 16)

CMSC330. Objects, Functional Programming, and lambda calculus

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

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

Weeks 6&7: Procedures and Parameter Passing

Programming Languages

OCaml Language Choices CMSC 330: Organization of Programming Languages

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?

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

CS 360 Programming Languages Interpreters

Chapter 5 Names, Binding, Type Checking and Scopes

CSE 413 Midterm, May 6, 2011 Sample Solution Page 1 of 8

Announcements. My office hours are today in Gates 160 from 1PM-3PM. Programming Project 3 checkpoint due tomorrow night at 11:59PM.

Attributes of Variable. Lecture 13: Run-Time Storage Management. Lifetime. Value & Location

Principles of Programming Languages Topic: Scope and Memory Professor Louis Steinberg Fall 2004

Qualifying Exam in Programming Languages and Compilers

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

G Programming Languages - Fall 2012

Run-time Environments

Programming Languages

Run-time Environments

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

CS558 Programming Languages. Winter 2013 Lecture 3

StackVsHeap SPL/2010 SPL/20

Begin at the beginning

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

CS558 Programming Languages

Where We Are. Lexical Analysis. Syntax Analysis. IR Generation. IR Optimization. Code Generation. Machine Code. Optimization.

Functions CHAPTER 5. FIGURE 1. Concrete syntax for the P 2 subset of Python. (In addition to that of P 1.)

Scope and Parameter Passing 1 / 19

! Those values must be stored somewhere! Therefore, variables must somehow be bound. ! How?

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

Cpt S 122 Data Structures. Course Review Midterm Exam # 2

CS153: Compilers Lecture 15: Local Optimization

Concepts Introduced in Chapter 7

COSE212: Programming Languages. Lecture 3 Functional Programming in OCaml

Functional Programming. Pure Functional Programming

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

Topics Covered Thus Far CMSC 330: Organization of Programming Languages

Types and Type Inference

CS558 Programming Languages

CSE 341: Programming Languages

JVM ByteCode Interpreter

CS422 - Programming Language Design

CS558 Programming Languages

CPS 506 Comparative Programming Languages. Programming Language

Heap, Variables, References, and Garbage. CS152. Chris Pollett. Oct. 13, 2008.

Typical Runtime Layout. Tiger Runtime Environments. Example: Nested Functions. Activation Trees. code. Memory Layout

Functions CHAPTER 5. FIGURE 1. Concrete syntax for the P 2 subset of Python. (In addition to that of P 1.)

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

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

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

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

Today: Revisit some objects. Programming Languages. Key data structure: Dictionaries. Using Dictionaries. CSE 130 : Winter 2009

Iterators. Lecture 24: Iterators & Exceptions. Implementing Iterators. When Good Programs Go Bad! - where! Abstract over control structures (in Clu)!

CSE341: Programming Languages Lecture 7 First-Class Functions. Dan Grossman Winter 2013

Names, Bindings, Scopes

CSE : Python Programming

Compiler Construction Lecture 05 A Simple Stack Machine. Lent Term, Lecturer: Timothy G. Griffin. Computer Laboratory University of Cambridge

CMSC 330: Organization of Programming Languages. OCaml Imperative Programming

Programming Assignment 2

Procedure and Object- Oriented Abstraction

Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach.

Code Generation. Lecture 12

They are a block of code plus the bindings to the environment they came from (Ragusa Idiom / function object).

Storage. Outline. Variables and Updating. Composite Variables. Storables Lifetime : Programming Languages. Course slides - Storage

Fundamental Concepts and Definitions

CS558 Programming Languages

Types, Type Inference and Unification

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

TAIL RECURSION, SCOPE, AND PROJECT 4 11

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

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

Programming Languages

UNIT 3

Transcription:

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 Monad

Recursion

Prototypical Example fact(n): if (n <= 1) then 1 else n * fact(n-1)

Thinking Recursively Add numbers in a list Print a list of numbers Check if a number is in a list (Live coding)

Tail Recursion (first-order case) slide 6 Function g makes a tail call to function f if return value of function f is return value of g Example tail call fun g(x) = if x>0 then f(x) else f(x)*2 not a tail call Optimization: can pop current activation record on a tail call Especially useful for recursive tail call because next activation record has exactly same form

Example of Tail Recursion slide 7 Calculate least power of 2 greater than y f(1,3) control return val x 1 y 3 control return val x 1 y 3 fun f(x,y) = if x>y then x else f(2*x, y); f(1,3) + 7; control return val x 2 y 3 control return val x 4 y 3

Tail Recursion Elimination slide 8 f(1,3) f(2,3) f(4,3) control return val x 1 y 3 control return val x 2 y 3 control return val x 4 y 3 fun f(x,y) = if x>y then x else f(2*x, y); f(1,3) + 7; Optimization pop followed by push - reuse activation record in place Tail recursive function is equivalent to iterative loop

Tail Recursion and Iteration slide 9 f(1,3) f(2,3) f(4,3) control control control return val return val return val x 1 x 2 x 4 y 3 y 3 y 3 fun f(x,y) = if x>y test function g(y) { then x var x = 1; else f(2*x, y); loop body while (!x>y) f(1,y); initial value } x = 2*x; return x;

Higher-order functions

Higher-Order Functions slide 11 Function passed as argument Need pointer to activation record higher up in stack Function returned as the result of function call Need to keep activation record of the returning function Functions that take function(s) as input and return functions as output are known as functionals

Return Function as Result slide 12 Language feature (e.g., Python, ML,...) Functions that return new functions Example: fun compose(f,g) = (fn x => g(f x)); Function is created dynamically Expression with free variables; values determined at runtime Function value is closure = env, code Code not compiled dynamically (in most languages) Need to maintain environment of the creating function

Closures slide 13 Function value is pair closure = env, code Statically scoped function must carry a link to its static environment with it Only needed if function is defined in a nested block When a function represented by a closure is called Allocate activation record for call (as always) Set the access link in the activation record using the environment pointer from the closure

Closures Function with free variables that are bound to values in the enclosing environment (lambda (x) (lambda (y) x+y)) closure def makeinc(x): def inc(y): # x is "closed" in the definition of inc return y + x return inc Note to self: illustrate closures in Python and C# (my examples)

What are closures good for? For changing your mind later! Replaces constants and variables with functions Replaces conditionals...

Return Function with Private State slide 16 fun mk_counter (init : int) = let val count = ref init fun counter(inc:int) = (count :=!count + inc;!count) in counter end; val c = mk_counter(1); c(2) + c(2); Function to make counter returns a closure How is correct value of count determined in c(2)?

Implementing Closures slide 17 Closures as used to maintain static environment of functions as they are passed around May need to keep activation records after function returns Stack (last-in-first-out) order fails! (why?) Possible stack implementation: Put activation records on heap Instead of explicit deallocation, invoke garbage collector as needed

Continuations

Continuations Representation of the control state of a program Data structure available to the programmer instead of hidden Contains the current stack and point in the computation Can be later used to return to that point

Remember Goto A: blah blah if something GOTO A else GOTO B B:... Flow control via textual labels mixes computation (beta-reductions) and representation (the text of the program)

Continuations continued Elegant concept for arbitrary flow control Computation in the past Current Continuation = current point + bound variables Computation in the future Note to self: illustrate continuations in Scheme (Wikipedia)

What are continuations good for? Everything control flow! Co-routines Exceptions Preserving flow in non-blocking I/O (rhymes!)

The continuation nature of exceptions function fact (n) { if (n < 0) throw "n < 0" ; else if (n == 0) return 1 ; else return n * fact(n-1) ; } function total_fact (n) { try { return fact(n) ; } catch (ex) { return false ; } } document.write("total_fact(10): " + total_fact(10)) ; document.write("total_fact(-1): " + total_fact(-1)) ;

The continuation nature of exceptions desugaring the previous slide function fact (n,r,t) { if (n < 0) t ("n < 0") else if (n == 0) r(1) else fact(n-1, function (t0) { r (n*t0) ; }, t) } total_fact(10, function (res) { document.write("total_fact(10): " + res) }) ; total_fact(-1, function (res) { document.write("total_fact(-1): " + res) }) ; function total_fact (n,ret) { fact (n,ret, function (ex) { ret(false) ; }) ; }

I/O and continuations Blocking (I/O in most systems) contents = fs.readfile(path); with contents do blah Blocks here until we have the result Non-blocking contents = fs.readfileasync(path); with contents do blah Uh-oh, we still don t have it How to solve this?

I/O and continuations Non-blocking fs.readfileasync(path, lambda(contents) { with contents do blah }); It s a callback! It s the current continuation of the blocking form JavaScript is FULL of this, so are jquery and node.js

Monads

Monads what is the problem? The problem: how to affect the world Problem is more prevalent in pure functional programming style No side-effects That s right: no side-effects! But you ve all seen it too!

No side effects?! Why? Easier to test: idempotent functions Easier to parallelize But the world is ALL about side-effects, right? Storage, network, UI,... Programs affect and control objects and activities in the real world

Example a Tracing monad def hypotenuse(x, y): return math.sqrt(math.pow(x, 2) + math.pow(y, 2)) Now we want to trace it, or affect the world in it: def hypotenuse(x, y): h = math.sqrt(math.pow(x, 2) + math.pow(y, 2)) print In hypotenuse + h return h

Example a Tracing monad def hypotenuse(x, y): h = math.sqrt(math.pow(x, 2) + math.pow(y, 2)) return h, In hypotenuse + h Signature was Signature now is float, float -> float float, float -> float, string > math.pow(hypotenuse(6, 16), 4);

What is a monad? It s a container An active container it has behavior to: Wrap itself around a [typed] value Bind functions together

What is a monad? [A type constructor, m] A function that builds values of that type a -> m a (what you d normally call a constructor in OOP) A function (bind) that combines values [of that type] with computations that produce values [of that type] m a -> (a -> m b) -> m b An unwrap function that shows what s inside