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

Similar documents
INF 212 ANALYSIS OF PROG. LANGS FUNCTION COMPOSITION. Instructors: Crista Lopes 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

Topic 7: Activation Records

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?

Continuations and Continuation-Passing Style

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

INF3110 Programming Languages Runtime Organization part II

INF3110 Programming Languages Runtime Organization part II

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

Short Notes of CS201

Chapter 5. Names, Bindings, and Scopes

CS201 - Introduction to Programming Glossary By

CS558 Programming Languages

CMSC 330: Organization of Programming Languages

Recap: Functions as first-class values

CS558 Programming Languages

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

Variables and Bindings

Chapter 1. Fundamentals of Higher Order Programming

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)

JVM ByteCode Interpreter

Compilers: The goal. Safe. e : ASM

Weeks 6&7: Procedures and Parameter Passing

functional programming in Python, part 2

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

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

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

CSE 341: Programming Languages

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

Programming Languages

Types and Type Inference

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

CS422 - Programming Language Design

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

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

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

Topic III. LISP : functions, recursion, and lists References: Chapter 3 of Concepts in programming languages by J. C. Mitchell. CUP, 2003.

Begin at the beginning

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

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

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

Chapter 5 Names, Binding, Type Checking and Scopes

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

CS558 Programming Languages

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

StackVsHeap SPL/2010 SPL/20

COSE212: Programming Languages. Lecture 3 Functional Programming in OCaml

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

OCaml Language Choices CMSC 330: Organization of Programming Languages

CS558 Programming Languages

Types, Type Inference and Unification

More Lambda Calculus and Intro to Type Systems

More Scheme CS 331. Quiz. 4. What is the length of the list (()()()())? Which element does (car (cdr (x y z))) extract from the list?

CS1 Lecture 5 Jan. 26, 2018

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

Concepts Introduced in Chapter 7

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

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

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

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

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

CS 360 Programming Languages Interpreters

Introduction to Concepts in Functional Programming. CS16: Introduction to Data Structures & Algorithms Spring 2017

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

Topics Covered Thus Far CMSC 330: Organization of Programming Languages

CSE : Python Programming

UNIT 3

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

Functional Programming. Pure Functional Programming

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

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

A Second Look At ML. Chapter Seven Modern Programming Languages, 2nd ed. 1

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

CS 345. Exceptions. Vitaly Shmatikov. slide 1

More Lambda Calculus and Intro to Type Systems

G Programming Languages - Fall 2012

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

CS558 Programming Languages

INF 212 ANALYSIS OF PROG. LANGS PROCEDURES & FUNCTIONS. Instructors: Kaj Dreef Copyright Instructors.

CPL 2016, week 10. Clojure functional core. Oleg Batrashev. April 11, Institute of Computer Science, Tartu, Estonia

G Programming Languages - Fall 2012

Programming for Engineers in Python

Functional Programming. Pure Functional Programming

G Programming Languages - Fall 2012

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

CS558 Programming Languages. Winter 2013 Lecture 3

Anonymous Functions CMSC 330: Organization of Programming Languages

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

Static Program Analysis Part 1 the TIP language

Run-time Environments

TAIL RECURSION, SCOPE, AND PROJECT 4 11

Run-time Environments

CS153: Compilers Lecture 15: Local Optimization

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

Transcription:

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

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 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 Function returned as the result of function call Functions that take function(s) as input and return functions as output: these 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 n Expression with free variables; values determined at runtime Function value is closure = áenv, codeñ 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

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

Implementing Closures slide 16 Closures as used to maintain static environment of functions as they are passed around May need to keep activation records after function returns 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:...

What are continuations good for? Co-routines Exceptions Preserving flow in non-blocking I/O

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) { Acts as a continuation return false ; } } document.write("total_fact(10): " + total_fact(10)) ; document.write("total_fact(-1): " + total_fact(-1)) ;

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!

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