Adapted with permission from: Seif Haridi KTH Peter Van Roy UCL. C. Varela; Adapted w. permission from S. Haridi and P. Van Roy 1

Similar documents
Adapted with permission from: Seif Haridi KTH Peter Van Roy UCL. C. Varela; Adapted w. permission from S. Haridi and P. Van Roy 1

Functional Programming: Lists, Pattern Matching, Recursive Programming (CTM Sections , 3.2, , 4.7.2)

Declarative Computation Model. Conditional. Case statement. Procedure values (2) Procedure values. Sequential declarative computation model

Declarative Programming Techniques

Declarative Programming Techniques

Accumulators. A Trivial Example in Oz. A Trivial Example in Prolog. MergeSort Example. Accumulators. Declarative Programming Techniques

Programming Language Concepts, CS2104 Lecture 3

And, even if it is square, we may not be able to use EROs to get to the identity matrix. Consider

Structuring the verification of heap-manipulating programs

A call-by-name lambda-calculus machine

CS 231: Algorithmic Problem Solving

The L Machines are very high-level, in two senses:

6.001 SICP September? Procedural abstraction example: sqrt (define try (lambda (guess x) (if (good-enuf? guess x) guess (try (improve guess x) x))))

COMP 204. Object Oriented Programming (OOP) Mathieu Blanchette

Lexical Analysis. DFA Minimization & Equivalence to Regular Expressions

G54FOP: Lecture 17 & 18 Denotational Semantics and Domain Theory III & IV

Lisp Introduction. Dr. Neil T. Dantam. Spring CSCI-498/598 RPM, Colorado School of Mines. Dantam (Mines CSCI, RPM) Lisp Spring / 88

Axiomatic Semantics. Stansifer Ch 2.4, Ch. 9 Winskel Ch.6 Slonneger and Kurtz Ch. 11 CSE

Reasoning About Imperative Programs. COS 441 Slides 10b

ITI Introduction to Computing II

CSE613: Parallel Programming, Spring 2012 Date: May 11. Final Exam. ( 11:15 AM 1:45 PM : 150 Minutes )

Recursion: Introduction and Correctness

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

Iris: Higher-Order Concurrent Separation Logic. Lecture 9: Concurrency Intro and Invariants

6.001 Recitation 22: Streams

2 Results I: Lifting Computer Science

A Short Introduction to Hoare Logic

Automatic Verification of Parameterized Data Structures

I. Numerical Computing

On-the-Fly Model Checking for Extended Action-Based Probabilistic Operators

Part I: Definitions and Properties

The Expressivity of Universal Timed CCP: Undecidability of Monadic FLTL and Closure Operators for Security

An Introduction to Z3

Theory of Computer Science. Theory of Computer Science. D7.1 Introduction. D7.2 Turing Machines as Words. D7.3 Special Halting Problem

Classical Program Logics: Hoare Logic, Weakest Liberal Preconditions

Designing Information Devices and Systems I Fall 2018 Lecture Notes Note Introduction to Linear Algebra the EECS Way

SMT BASICS WS 2017/2018 ( ) LOGIC SATISFIABILITY MODULO THEORIES. Institute for Formal Models and Verification Johannes Kepler Universität Linz

Handout 8: Computation & Hierarchical parsing II. Compute initial state set S 0 Compute initial state set S 0

A linear equation in two variables is generally written as follows equation in three variables can be written as

Imperative Insertion Sort

Programming Language Concepts, cs2104 Tutorial 1. Answers

Synchronous Reactive Systems

Introduction to lambda calculus Part 2

Functional Programming with F# Overview and Basic Concepts

MATHEMATICAL OBJECTS in

Computational Models Lecture 8 1

Halting and Equivalence of Program Schemes in Models of Arbitrary Theories

Computational Models Lecture 8 1

Review. Principles of Programming Languages. Equality. The Diamond Property. The Church-Rosser Theorem. Corollaries. CSE 230: Winter 2007

Programming with classical quantum datatypes

Designing Information Devices and Systems I Spring 2018 Lecture Notes Note Introduction to Linear Algebra the EECS Way

CTL satisfability via tableau A C++ implementation

Lecture 4. Finite Automata and Safe State Machines (SSM) Daniel Kästner AbsInt GmbH 2012

The Viterbi Algorithm EECS 869: Error Control Coding Fall 2009

ITI Introduction to Computing II

Queues. Principles of Computer Science II. Basic features of Queues

Lexical Analysis Part II: Constructing a Scanner from Regular Expressions

Elaborating evaluation-order polymorphism

Computer Science Introductory Course MSc - Introduction to Java

Operational Semantics

CS 4110 Programming Languages & Logics. Lecture 16 Programming in the λ-calculus

CSC 7101: Programming Language Structures 1. Axiomatic Semantics. Stansifer Ch 2.4, Ch. 9 Winskel Ch.6 Slonneger and Kurtz Ch. 11.

Course Announcements. Bacon is due next Monday. Next lab is about drawing UIs. Today s lecture will help thinking about your DB interface.

An Early (1971) Conversation. Logic Programming (PLP 11.3) Horn Clauses Introduction to Prolog: Resolution, Unification.

Why Functional Programming Matters. John Hughes & Mary Sheeran

Theory of Computation. Theory of Computation

Algorithms 2/6/2018. Algorithms. Enough Mathematical Appetizers! Algorithm Examples. Algorithms. Algorithm Examples. Algorithm Examples

Automata Theory CS S-12 Turing Machine Modifications

Final Exam Comments. UVa - cs302: Theory of Computation Spring < Total

Logic Programming in a Fragment of Intuitionistic Linear Logic

Analysis of Algorithms. Outline 1 Introduction Basic Definitions Ordered Trees. Fibonacci Heaps. Andres Mendez-Vazquez. October 29, Notes.

Modern Functional Programming and Actors With Scala and Akka

Limitations of OCAML records

Coinductive big-step semantics and Hoare logics for nontermination

Computer-Aided Program Design

From CCS to Hybrid π via baby steps. Bill Rounds CSE, U of Michigan

CHEE 222: PROCESS DYNAMICS AND NUMERICAL METHODS

Principles of Program Analysis: Control Flow Analysis

Visibly Linear Dynamic Logic

Compilers. Lexical analysis. Yannis Smaragdakis, U. Athens (original slides by Sam

Go Tutorial. Ian Lance Taylor. Introduction. Why? Language. Go Tutorial. Ian Lance Taylor. GCC Summit, October 27, 2010

Harvard CS 121 and CSCI E-207 Lecture 10: CFLs: PDAs, Closure Properties, and Non-CFLs

11. Automata and languages, cellular automata, grammars, L-systems

Python. chrysn

Iris: Higher-Order Concurrent Separation Logic. Lecture 6: Case Study: foldr

an efficient procedure for the decision problem. We illustrate this phenomenon for the Satisfiability problem.

Locksmith: Context-Sensitive Correlation Analysis for Race Detection

A Reconfigurable Quantum Computer

Algorithms and Their Complexity

1 Some loose ends from last time

Automata-based Verification - III

Outline. A recursive function follows the structure of inductively-defined data.

Program Verification Using Separation Logic

Mathematical Induction

Decidability and Undecidability

What is SSA? each assignment to a variable is given a unique name all of the uses reached by that assignment are renamed

Decision Procedures. Jochen Hoenicke. Software Engineering Albert-Ludwigs-University Freiburg. Winter Term 2016/17

MiniMat: Matrix Language in OCaml LLVM

Non-Markovian Control in the Situation Calculus

Solutions to EoPL3 Exercises

Transcription:

Higher-Order Programming: Iterative computation (CTM Section 3.2) Closures, procedural abstraction, genericity, instantiation, embedding (CTM Section 3.6.1) Carlos Varela RPI September 15, 2017 Adapted with permission from: Seif Haridi KTH Peter Van Roy UCL C. Varela; Adapted w. permission from S. Haridi and P. Van Roy 1

Iterative computation An iterative computation is one whose execution stack is bounded by a constant, indepent of the length of the computation Iterative computation starts with an initial state S 0, and transforms the state in a number of steps until a final state S final is reached: s s... s 0 1 final C. Varela; Adapted w/permission from S. Haridi and P. Van Roy 2

The general scheme fun {Iterate S i } if {IsDone S i } then S i else S i+1 in S i+1 = {Transform S i } {Iterate S i+1 } IsDone and Transform are problem depent C. Varela; Adapted w/permission from S. Haridi and P. Van Roy 3

The computation model STACK : [ R={Iterate S 0 }] STACK : [ S 1 = {Transform S 0 }, R={Iterate S 1 } ] STACK : [ R={Iterate S i }] STACK : [ S i+1 = {Transform S i }, R={Iterate S i+1 } ] STACK : [ R={Iterate S i+1 }] C. Varela; Adapted w/permission from S. Haridi and P. Van Roy 4

Newton s method for the square root of a positive real number Given a real number x, start with a guess g, and improve this guess iteratively until it is accurate enough The improved guess g is the average of g and x/g: g! = ( g + x / g) / 2 ε = g x ε! = g! x For g! to be a better guess than g: ε! < ε ε! = g! x = ( g + x / g) / 2 x = ε 2 / 2 g i.e. ε 2 / 2 g < ε, ε / 2 g < 1 i. e. ε < 2g, g x < 2g, 0 < g + x C. Varela; Adapted w/permission from S. Haridi and P. Van Roy 5

Newton s method for the square root of a positive real number Given a real number x, start with a guess g, and improve this guess iteratively until it is accurate enough The improved guess g is the average of g and x/g: Accurate enough is defined as: x g 2 / x < 0.00001 C. Varela; Adapted w/permission from S. Haridi and P. Van Roy 6

SqrtIter fun {SqrtIter Guess X} if {GoodEnough Guess X} then Guess else Guess1 = {Improve Guess X} in {SqrtIter Guess1 X} Compare to the general scheme: The state is the pair Guess and X IsDone is implemented by the procedure GoodEnough Transform is implemented by the procedure Improve C. Varela; Adapted w/permission from S. Haridi and P. Van Roy 7

The program version 1 fun {Sqrt X} Guess = 1.0 in {SqrtIter Guess X} fun {SqrtIter Guess X} if {GoodEnough Guess X} then Guess else {SqrtIter {Improve Guess X} X} fun {Improve Guess X} (Guess + X/Guess)/2.0 fun {GoodEnough Guess X} {Abs X - Guess*Guess}/X < 0.00001 C. Varela; Adapted w/permission from S. Haridi and P. Van Roy 8

Using local procedures The main procedure Sqrt uses the helper procedures SqrtIter, GoodEnough, Improve, and Abs SqrtIter is only needed inside Sqrt GoodEnough and Improve are only needed inside SqrtIter Abs (absolute value) is a general utility The general idea is that helper procedures should not be visible globally, but only locally C. Varela; Adapted w/permission from S. Haridi and P. Van Roy 9

Sqrt version 2 local fun {SqrtIter Guess X} if {GoodEnough Guess X} then Guess else {SqrtIter {Improve Guess X} X} fun {Improve Guess X} (Guess + X/Guess)/2.0 fun {GoodEnough Guess X} {Abs X - Guess*Guess}/X < 0.000001 in fun {Sqrt X} Guess = 1.0 in {SqrtIter Guess X} C. Varela; Adapted w/permission from S. Haridi and P. Van Roy 10

Sqrt version 3 Define GoodEnough and Improve inside SqrtIter local fun {SqrtIter Guess X} fun {Improve} (Guess + X/Guess)/2.0 fun {GoodEnough} {Abs X - Guess*Guess}/X < 0.000001 in if {GoodEnough} then Guess else {SqrtIter {Improve} X} in fun {Sqrt X} Guess = 1.0 in {SqrtIter Guess X} C. Varela; Adapted w/permission from S. Haridi and P. Van Roy 11

Sqrt version 3 Define GoodEnough and Improve inside SqrtIter local fun {SqrtIter Guess X} fun {Improve} (Guess + X/Guess)/2.0 fun {GoodEnough} {Abs X - Guess*Guess}/X < 0.000001 in if {GoodEnough} then Guess else {SqrtIter {Improve} X} in fun {Sqrt X} Guess = 1.0 in {SqrtIter Guess X} The program has a single drawback: on each iteration two procedure values are created, one for Improve and one for GoodEnough C. Varela; Adapted w/permission from S. Haridi and P. Van Roy 12

Sqrt final version fun {Sqrt X} fun {Improve Guess} (Guess + X/Guess)/2.0 fun {GoodEnough Guess} {Abs X - Guess*Guess}/X < 0.000001 fun {SqrtIter Guess} if {GoodEnough Guess} then Guess else {SqrtIter {Improve Guess} } Guess = 1.0 in {SqrtIter Guess} The final version is a compromise between abstraction and efficiency C. Varela; Adapted w/permission from S. Haridi and P. Van Roy 13

From a general scheme to a control abstraction (1) fun {Iterate S i } if {IsDone S i } then S i else S i+1 in S i+1 = {Transform S i } {Iterate S i+1 } IsDone and Transform are problem depent C. Varela; Adapted w/permission from S. Haridi and P. Van Roy 14

From a general scheme to a control abstraction (2) fun {Iterate S IsDone Transform} if {IsDone S} then S else S1 in S1 = {Transform S} {Iterate S1 IsDone Transform} fun {Iterate S i } if {IsDone S i } then S i else S i+1 in S i+1 = {Transform S i } {Iterate S i+1 } C. Varela; Adapted w/permission from S. Haridi and P. Van Roy 15

Sqrt using the Iterate abstraction fun {Sqrt X} fun {Improve Guess} (Guess + X/Guess)/2.0 fun {GoodEnough Guess} {Abs X - Guess*Guess}/X < 0.000001 Guess = 1.0 in {Iterate Guess GoodEnough Improve} C. Varela; Adapted w/permission from S. Haridi and P. Van Roy 16

Sqrt using the control abstraction fun {Sqrt X} {Iterate } 1.0 fun {$ G} {Abs X - G*G}/X < 0.000001 fun {$ G} (G + X/G)/2.0 Iterate could become a linguistic abstraction C. Varela; Adapted w/permission from S. Haridi and P. Van Roy 17

Sqrt in Haskell let sqrt x = head (dropwhile (not. goodenough) sqrtguesses) where goodenough guess = (abs (x guess*guess))/x < 0.00001 improve guess = (guess + x/guess)/2.0 sqrtguesses = 1:(map improve sqrtguesses) This sqrt example uses infinite lists enabled by lazy evaluation, and the map control abstraction. C. Varela; Adapted w/permission from S. Haridi and P. Van Roy 18

Higher-order programming Higher-order programming = the set of programming techniques that are possible with procedure values (lexically-scoped closures) Basic operations Procedural abstraction: creating procedure values with lexical scoping Genericity: procedure values as arguments Instantiation: procedure values as return values Embedding: procedure values in data structures Higher-order programming is the foundation of component-based programming and object-oriented programming C. Varela; Adapted w/permission from S. Haridi and P. Van Roy 19

Procedural abstraction Procedural abstraction is the ability to convert any statement into a procedure value A procedure value is usually called a closure, or more precisely, a lexically-scoped closure A procedure value is a pair: it combines the procedure code with the environment where the procedure was created (the contextual environment) Basic scheme: Consider any statement <s> Convert it into a procedure value: P = proc {$} <s> Executing {P} has exactly the same effect as executing <s> C. Varela; Adapted w/permission from S. Haridi and P. Van Roy 20

Procedural abstraction fun {AndThen B1 B2} if B1 then B2 else false C. Varela; Adapted w/permission from S. Haridi and P. Van Roy 21

Procedural abstraction fun {AndThen B1 B2} if {B1} then {B2} else false C. Varela; Adapted w/permission from S. Haridi and P. Van Roy 22

A common limitation Most popular imperative languages (C, Pascal) do not have procedure values They have only half of the pair: variables can reference procedure code, but there is no contextual environment This means that control abstractions cannot be programmed in these languages They provide a predefined set of control abstractions (for, while loops, if statement) Generic operations are still possible They can often get by with just the procedure code. The contextual environment is often empty. The limitation is due to the way memory is managed in these languages Part of the store is put on the stack and deallocated when the stack is deallocated This is supposed to make memory management simpler for the programmer on systems that have no garbage collection It means that contextual environments cannot be created, since they would be full of dangling pointers Object-oriented programming languages can use objects to encode procedure values by making external references (contextual environment) instance variables. C. Varela; Adapted w/permission from S. Haridi and P. Van Roy 23

Genericity Replace specific entities (zero 0 and addition +) by function arguments The same routine can do the sum, the product, the logical or, etc. fun {SumList L} case L of nil then 0 [] X L2 then X+{SumList L2} fun {FoldR L F U} case L of nil then U [] X L2 then {F X {FoldR L2 F U}} C. Varela; Adapted w/permission from S. Haridi and P. Van Roy 24

Instantiation fun {FoldFactory F U} fun {FoldR L} case L of nil then U [] X L2 then {F X {FoldR L2}} in FoldR Instantiation is when a procedure returns a procedure value as its result Calling {FoldFactory fun {$ A B} A+B 0} returns a function that behaves identically to SumList, which is an «instance» of a folding function C. Varela; Adapted w/permission from S. Haridi and P. Van Roy 25

Embedding Embedding is when procedure values are put in data structures Embedding has many uses: Modules: a module is a record that groups together a set of related operations Software components: a software component is a generic function that takes a set of modules as its arguments and returns a new module. It can be seen as specifying a module in terms of the modules it needs. Delayed evaluation (also called explicit lazy evaluation): build just a small part of a data structure, with functions at the extremities that can be called to build more. The consumer can control explicitly how much of the data structure is built. C. Varela; Adapted w/permission from S. Haridi and P. Van Roy 26

Exercises 18. CTM Exercise 3.10.5 (page 230) 19. Suppose you have two sorted lists. Merging is a simple method to obtain an again sorted list containing the elements from both lists. Write a Merge function that is generic with respect to the order relation. 20. Instantiate the FoldFactory to create a ProductList function to multiply all the elements of a list. 21. Create an AddFactory function that takes a list of numbers and returns a list of functions that can add by those numbers, e.g. {AddFactory [1 2]} => [Inc1 Inc2] where Inc1 and Inc2 are functions to increment a number by 1 and 2 respectively, e.g., {Inc2 3} => 5. 22. Implement exercises 18-21 in both Oz and Haskell. C. Varela; Adapted w/permission from S. Haridi and P. Van Roy 27