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

Size: px
Start display at page:

## Transcription

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

3 Recursion

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

5 Thinking Recursively Add numbers in a list Print a list of numbers Check if a number is in a list

6 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

7 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

8 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

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

10 Higher-order functions

11 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

12 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

13 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

14 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

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

16 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

17 Continuations

18 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

19 Remember Goto A: blah blah if something GOTO A else GOTO B B:...

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

21 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)) ;

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

23 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

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

26 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

27 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

28 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);

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

30 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

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

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

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

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

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

### Topic 7: Activation Records

Topic 7: Activation Records Compiler Design Prof. Hanjun Kim CoreLab (Compiler Research Lab) POSTECH 1 Storage Organization Stack Free Memory Heap Static Code 2 ELF file format example Executable Object

### Programming Languages

CSE 130 : Spring 2011 Programming Languages Lecture 13: What s in a Name? Ranjit Jhala UC San Diego Next: What s in a name? More precisely: How should programmer think of data What does a variable x really

### Next: What s in a name? Programming Languages. Data model in functional PL. What s in a name? CSE 130 : Fall Lecture 13: What s in a Name?

Next: What s in a name? CSE 13 : Fall 211 Programming Languages Lecture 13: What s in a Name? More precisely: How should programmer think of data What does a variable x really mean? Ranjit Jhala UC San

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

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

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

### INF3110 Programming Languages Runtime Organization part II

INF3110 Programming Languages Runtime Organization part II 10/13/16 1 Higher-Order Functions Language features Functions passed as arguments Functions that return functions from nested blocks Need to maintain

### INF3110 Programming Languages Runtime Organization part II

INF3110 Programming Languages Runtime Organization part II 10/24/17 1 Today: Higher-Order Functions, and Objects at runtime Higher-order functions: Functions passed as arguments Functions that return functions

### 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 Summary 1. Predictive Parsing 2. Large Step Operational Semantics (Natural) 3. Small Step Operational Semantics

### Short Notes of CS201

#includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system

### Chapter 5. Names, Bindings, and Scopes

Chapter 5 Names, Bindings, and Scopes Chapter 5 Topics Introduction Names Variables The Concept of Binding Scope Scope and Lifetime Referencing Environments Named Constants 1-2 Introduction Imperative

### CS201 - Introduction to Programming Glossary By

CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with

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

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

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

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

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

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

### Chapter 1. Fundamentals of Higher Order Programming

Chapter 1 Fundamentals of Higher Order Programming 1 The Elements of Programming Any powerful language features: so does Scheme primitive data procedures combinations abstraction We will see that Scheme

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

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

Compiler Construction Lent Term 15 Lectures 10, 11 (of 16) 1. Slang.2 (Lecture 10) 1. In lecture code walk of slang2_derive 2. Assorted topics (Lecture 11) 1. Exceptions 2. Objects 3. Stacks vs. Register

### JVM ByteCode Interpreter

JVM ByteCode Interpreter written in Haskell (In under 1000 Lines of Code) By Louis Jenkins Presentation Schedule ( 15 Minutes) Discuss and Run the Virtual Machine first

### Compilers: The goal. Safe. e : ASM

Compilers: The goal What s our goal with compilers? Take a high level language, turn it into a low level language In a semantics preserving way. e : ML Safe e : ASM 1 Compilers: The goal What s our goal

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

### functional programming in Python, part 2

Programming Languages Week 2 functional programming in Python, part 2 College of Information Science and Engineering Ritsumeikan University review of part 1 eliminating assignment makes programs easier

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

Principles of Programming Languages Topic: Scope and Memory Professor Louis Steinberg Fall 2004 CS 314, LS,BR,LTM: Scope and Memory 1 Review Functions as first-class objects What can you do with an integer?

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

IR Generation Announcements My office hours are today in Gates 160 from 1PM-3PM. Programming Project 3 checkpoint due tomorrow night at 11:59PM. This is a hard deadline and no late submissions will be

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

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

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

### Programming Languages

CSE 130 : Fall 2009 Programming Languages Lecture 13: Whats in a name? Ranjit Jhala UC San Diego f = open( foo.txt, read ) f.readlines() for l in f.readlines(): f.close ou now know enough to do PA5

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

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

CSE 130 : Winter 2009 Programming Languages Lecture 11: What s in a Name? Today: Revisit some objects Exploit features and build powerful expressions Base: int, float, complex Sequence: string, tuple,

### CS422 - Programming Language Design

1 CS422 - Programming Language Design Elements of Functional Programming Grigore Roşu Department of Computer Science University of Illinois at Urbana-Champaign 2 The two languages that we defined so far

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

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

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

CHAPTER 5 Functions The main ideas in this chapter are: first-class functions: functions are values that can be passed as arguments to other functions, returned from functions, stored in lists and dictionaries,

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

Topic III LISP : functions, recursion, and lists References: Chapter 3 of Concepts in programming languages by J. C. Mitchell. CUP, 2003. Chapters 5( 4.5) and 13( 1) of Programming languages: Design and

### Begin at the beginning

Begin at the beginning Expressions (Syntax) Exec-time Dynamic Values (Semantics) Compile-time Static Types 1. Programmer enters expression 2. ML checks if expression is well-typed Using a precise set of

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

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

Heap, Variables, References, and Garbage. CS152. Chris Pollett. Oct. 13, 2008. Outline. Dynamic Allocation. Variables and Constants. Aliases and Problems. Garbage. Introduction. On Wednesday, we were talking

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

INF 212 ANALYSIS OF PROG. LANGS ELEMENTS OF IMPERATIVE PROGRAMMING STYLE Instructors: Crista Lopes Copyright Instructors. Objectives Level up on things that you may already know Machine model of imperative

### Chapter 5 Names, Binding, Type Checking and Scopes

Chapter 5 Names, Binding, Type Checking and Scopes Names - We discuss all user-defined names here - Design issues for names: -Maximum length? - Are connector characters allowed? - Are names case sensitive?

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

Compiler Construction Lecture 05 A Simple Stack Machine Lent Term, 2015 Lecturer: Timothy G. Griffin Computer Laboratory University of Cambridge 1 Where are we going? When we derived the stack machine

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

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

### StackVsHeap SPL/2010 SPL/20

StackVsHeap Objectives Memory management central shared resource in multiprocessing RTE memory models that are used in Java and C++ services for Java/C++ programmer from RTE (JVM / OS). Perspectives of

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

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

Where We Are Source Code Lexical Analysis Syntax Analysis Semantic Analysis IR Generation IR Optimization Code Generation Optimization Machine Code Where We Are Source Code Lexical Analysis Syntax Analysis

### OCaml Language Choices CMSC 330: Organization of Programming Languages

OCaml Language Choices CMSC 330: Organization of Programming Languages! Implicit or explicit declarations?! Explicit variables must be introduced with let before use! But you don t need to specify types

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

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

### More Lambda Calculus and Intro to Type Systems

More Lambda Calculus and Intro to Type Systems Plan Heavy Class Participation Thus, wake up! Lambda Calculus How is it related to real life? Encodings Fixed points Type Systems Overview Static, Dyamic

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

More Scheme CS 331 Quiz 1. What is (car ((2) 3 4))? (2) 2. What is (cdr ((2) (3) (4)))? ((3)(4)) 3. What is (cons 2 (2 3 4))? (2 2 3 4) 4. What is the length of the list (()()()())? 4 5. Which element

### CS1 Lecture 5 Jan. 26, 2018

CS1 Lecture 5 Jan. 26, 2018 HW1 due Monday, 9:00am. Notes: Do not write all the code at once (for Q1 and 2) before starting to test. Take tiny steps. Write a few lines test... add a line or two test...

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

Subroutines and Control Abstraction Textbook, Chapter 8 1 Subroutines and Control Abstraction Mechanisms for process abstraction Single entry (except FORTRAN, PL/I) Caller is suspended Control returns

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

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

A Binding Question! Variables are bound (dynamically) to values Subprogram Activation! Those values must be stored somewhere! Therefore, variables must somehow be bound to memory locations! How? Function

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

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

CSE341: Programming Languages Lecture 7 First-Class Functions Dan Grossman Winter 2013 What is functional programming? Functional programming can mean a few different things: 1. Avoiding mutation in most/all

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

Attributes of Variable Lecture 13 Run-Time Storage Management CSC 131 Kim Bruce Scope Lifetime Location Value Done! Lifetime Value & Location FORTRAN - all allocated statically - Stack-based (C/C++/Java/Pascal/...)

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

Cpt S 122 Data Structures Course Review Midterm Exam # 2 Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Midterm Exam 2 When: Monday (11/05) 12:10 pm -1pm

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

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

Introduction to Concepts in Functional Programming CS16: Introduction to Data Structures & Algorithms Spring 2017 Outline Functions State Functions as building blocks Higher order functions Map Reduce

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

CS 6A Scheme Summer 207 Discussion 0: July 25, 207 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,

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

### CSE : Python Programming

CSE 399-004: Python Programming Lecture 10: Functional programming, Memoization March 26, 2007 http://www.seas.upenn.edu/~cse39904/ Announcements Should have received email about meeting times Length:

### UNIT 3

UNIT 3 Presentation Outline Sequence control with expressions Conditional Statements, Loops Exception Handling Subprogram definition and activation Simple and Recursive Subprogram Subprogram Environment

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

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

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

CHAPTER 5 Functions The main ideas in this chapter are: first-class functions: functions are values that can be passed as arguments to other functions, returned from functions, stored in lists and dictionaries,

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

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

A Second Look At ML Chapter Seven Modern Programming Languages, 2nd ed. 1 Outline Patterns Local variable definitions A sorting example Chapter Seven Modern Programming Languages, 2nd ed. 2 Two Patterns

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

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

Begin at the beginning Epressions (Synta) Compile-time Static Eec-time Dynamic Types Values (Semantics) 1. Programmer enters epression 2. ML checks if epression is well-typed Using a precise set of rules,

### CS 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 Lambda Calculus and Intro to Type Systems

More Lambda Calculus and Intro to Type Systems #1 One Slide Summary The lambda calculus is a model of computation or a programming language that is as expressive as a Turing machine. The lambda calculus

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

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

### CS558 Programming Languages

CS558 Programming Languages Winter 2018 Lecture 7b Andrew Tolmach Portland State University 1994-2018 Dynamic Type Checking Static type checking offers the great advantage of catching errors early And

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

INF 212 ANALYSIS OF PROG. LANGS PROCEDURES & FUNCTIONS Instructors: Kaj Dreef Copyright Instructors. Subroutines aka Procedures Historically: blocks of instructions executed several times during program

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

CPL 2016, week 10 Clojure functional core Oleg Batrashev Institute of Computer Science, Tartu, Estonia April 11, 2016 Overview Today Clojure language core Next weeks Immutable data structures Clojure simple

### G Programming Languages - Fall 2012

G22.2110-003 Programming Languages - Fall 2012 Lecture 2 Thomas Wies New York University Review Last week Programming Languages Overview Syntax and Semantics Grammars and Regular Expressions High-level

### Programming for Engineers in Python

Programming for Engineers in Python Lecture 5: Object Oriented Programming Autumn 2011-12 1 Lecture 4 Highlights Tuples, Dictionaries Sorting Lists Modular programming Data analysis: text categorization

### Functional Programming. Pure Functional Programming

Functional Programming With examples in F# Pure Functional Programming Functional programming involves evaluating expressions rather than executing commands. Computation is largely performed by applying

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

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

Intro Let s take some time to talk about LISP. It stands for LISt Processing a way of coding using only lists! It sounds pretty radical, and it is. There are lots of cool things to know about LISP; if

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

### Anonymous Functions CMSC 330: Organization of Programming Languages

Anonymous Functions CMSC 330: Organization of Programming Languages Recall code blocks in Ruby (1..10).each { x print x Here, we can think of { x print x as a function OCaml 2 Higher Order Functions 1

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

### Static Program Analysis Part 1 the TIP language

Static Program Analysis Part 1 the TIP language http://cs.au.dk/~amoeller/spa/ Anders Møller & Michael I. Schwartzbach Computer Science, Aarhus University Questions about programs Does the program terminate

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

### TAIL RECURSION, SCOPE, AND PROJECT 4 11

TAIL RECURSION, SCOPE, AND PROJECT 4 11 COMPUTER SCIENCE 61A Noveber 12, 2012 1 Tail Recursion Today we will look at Tail Recursion and Tail Call Optimizations in Scheme, and how they relate to iteration

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