Higher order procedures procedures as types

Similar documents
Higher-Order Procedures

6.001 SICP. Types. Types compound data. Types simple data. Types. Types procedures

Administrivia. Simple data types

Procedural abstraction SICP Data abstractions. The universe of procedures forsqrt. Procedural abstraction example: sqrt

6.001 Notes: Section 6.1

University of Massachusetts Lowell

Introduction to Scheme

CS450 - Structure of Higher Level Languages

Imperative, OO and Functional Languages A C program is

Why do we need an interpreter? SICP Interpretation part 1. Role of each part of the interpreter. 1. Arithmetic calculator.

An introduction to Scheme

Below are example solutions for each of the questions. These are not the only possible answers, but they are the most common ones.

MORE SCHEME. 1 What Would Scheme Print? COMPUTER SCIENCE MENTORS 61A. October 30 to November 3, Solution: Solutions begin on the following page.

Organization of Programming Languages CS3200/5200N. Lecture 11

CS 61A Interpreters, Tail Calls, Macros, Streams, Iterators. Spring 2019 Guerrilla Section 5: April 20, Interpreters.

11/6/17. Functional programming. FP Foundations, Scheme (2) LISP Data Types. LISP Data Types. LISP Data Types. Scheme. LISP: John McCarthy 1958 MIT

Introduction to ACL2. CS 680 Formal Methods for Computer Verification. Jeremy Johnson Drexel University

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017

Scheme Quick Reference

Turtles All The Way Down

Scheme Quick Reference

Functional Programming. Pure Functional Programming

CS 314 Principles of Programming Languages

Fall Semester, The Metacircular Evaluator. Today we shift perspective from that of a user of computer langugaes to that of a designer of

COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen

Scheme. Functional Programming. Lambda Calculus. CSC 4101: Programming Languages 1. Textbook, Sections , 13.7

Scheme Tutorial. Introduction. The Structure of Scheme Programs. Syntax

CS 480. Lisp J. Kosecka George Mason University. Lisp Slides

cs61amt2_4 CS 61A Midterm #2 ver March 2, 1998 Exam version: A Your name login: cs61a- Discussion section number TA's name

Notes on Higher Order Programming in Scheme. by Alexander Stepanov

LECTURE 16. Functional Programming

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

SCHEME 7. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. October 29, 2015

Streams and Evalutation Strategies

An Introduction to Scheme

Functional Languages. Hwansoo Han

Functional programming with Common Lisp

CS 342 Lecture 6 Scheme Procedures and Closures By: Hridesh Rajan

User-defined Functions. Conditional Expressions in Scheme

CS115 - Module 9 - filter, map, and friends

April 2 to April 4, 2018

Chapter 1. Fundamentals of Higher Order Programming

Streams, Delayed Evaluation and a Normal Order Interpreter. CS 550 Programming Languages Jeremy Johnson

Fall 2018 Discussion 8: October 24, 2018 Solutions. 1 Introduction. 2 Primitives

Typed Scheme: Scheme with Static Types

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

Using Symbols in Expressions (1) evaluate sub-expressions... Number. ( ) machine code to add

CS 61A Midterm #2 ver March 2, 1998 Exam version: A. Your name. login: cs61a- Discussion section number. TA's name

STREAMS 10. Basics of Streams. Practice with Streams COMPUTER SCIENCE 61AS. 1. What is a stream? 2. How does memoization work?

Scheme: Data. CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Monday, April 3, Glenn G.

Documentation for LISP in BASIC

Lambda Calculus and Lambda notation in Lisp II. Based on Prof. Gotshalks notes on Lambda Calculus and Chapter 9 in Wilensky.

Common LISP-Introduction

61A LECTURE 18 SCHEME. Steven Tang and Eric Tzeng July 24, 2013

HIERARCHICAL DATA What is a Tree? How is it different from a Deep List? When would you use one over the other?

6.184 Lecture 4. Interpretation. Tweaked by Ben Vandiver Compiled by Mike Phillips Original material by Eric Grimson

Functional Programming - 2. Higher Order Functions

STREAMS 10. Basics of Streams. Practice with Streams COMPUTER SCIENCE 61AS. 1. What is a stream?

Principles of Programming Languages

Normal Order (Lazy) Evaluation SICP. Applicative Order vs. Normal (Lazy) Order. Applicative vs. Normal? How can we implement lazy evaluation?

Functional Programming

Symbolic Programming. Dr. Zoran Duric () Symbolic Programming 1/ 89 August 28, / 89

FP Foundations, Scheme

YOUR NAME PLEASE: *** SOLUTIONS ***

Principles of Programming Languages Topic: Functional Programming Professor L. Thorne McCarty Spring 2003

Scheme as implemented by Racket

CSE 341 Section Handout #6 Cheat Sheet

Programming Systems in Artificial Intelligence Functional Programming

6.034 Artificial Intelligence February 9, 2007 Recitation # 1. (b) Draw the tree structure corresponding to the following list.

Scheme in Scheme: The Metacircular Evaluator Eval and Apply

6.001: Structure and Interpretation of Computer Programs

SCHEME AND CALCULATOR 5b

Announcements. The current topic: Scheme. Review: BST functions. Review: Representing trees in Scheme. Reminder: Lab 2 is due on Monday at 10:30 am.

6.037 Lecture 4. Interpretation. What is an interpreter? Why do we need an interpreter? Stages of an interpreter. Role of each part of the interpreter

CS61A Midterm 2 Review (v1.1)

1.3. Conditional expressions To express case distinctions like

CS 314 Principles of Programming Languages

A general introduction to Functional Programming using Haskell

Introduction to Functional Programming

UNIVERSITY OF TORONTO Faculty of Arts and Science. Midterm Sample Solutions CSC324H1 Duration: 50 minutes Instructor(s): David Liu.

Lecture 4: Higher Order Functions

CSc 372. Comparative Programming Languages. 36 : Scheme Conditional Expressions. Department of Computer Science University of Arizona

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

CS 314 Principles of Programming Languages. Lecture 16

6.037 Lecture 7B. Scheme Variants Normal Order Lazy Evaluation Streams

Streams. CS21b: Structure and Interpretation of Computer Programs Spring Term, 2004

Chapter 15 Functional Programming Languages

LECTURE 17. Expressions and Assignment

A Brief Introduction to Scheme (II)

Delayed Expressions Fall 2017 Discussion 9: November 8, Iterables and Iterators. For Loops. Other Iterable Uses

Introduction to LISP. York University Department of Computer Science and Engineering. York University- CSE V.

INF4820: Algorithms for Artificial Intelligence and Natural Language Processing. Common Lisp Fundamentals

Functional Programming Languages (FPL)

Modern Programming Languages. Lecture LISP Programming Language An Introduction

Problem Set 4: Streams and Lazy Evaluation

Category Theory & Functional Data Abstraction

CSCC24 Functional Programming Scheme Part 2

Vectors in Scheme. Data Structures in Scheme

Func%onal Programming in Scheme and Lisp

CSC 533: Programming Languages. Spring 2015

Transcription:

Higher order procedures procedures as types Today s topics Review of types of objects and procedures Procedural abstractions Capturing patterns across procedures Higher Order Procedures Note: Lecture ends with examples. We might not do all examples, depending on time. 1

Types (+ 5 10) ==> 15 (+ "hi 5) ;The object "hi", passed as the first argument to integer-add, is not the correct type Addition is not defined for strings 2

Types simple data Simple Data Number Integer -7 14 204689832123075 Real 3.14159 7.89211 Rational 11/12 7/8 5/16 String Boolean #t #f Names (symbols) Hello Goodbye fact ifact sort We will use this for notational purposes only to reason about our code. Scheme does not directly check types of arguments as part of its processing (weakly typed language). 3

Types compound data Pair<A,B> (cons 1 2) has type Pair<number, number> (cons Hello 5) has type Pair<string, number> List<A> (the same as Pair<A, List<A> or nil>) (list 1 2 3) has type List<number> (list 1 string 3) has type List<number or string> 4

Types procedures Since procedures operate on objects, and return values, we can define their types as well. We will denote a procedures type by indicating the types of each of its arguments, and the type of the returned value, plus the symbol to indicate that the arguments are mapped to the return value sin has type number number * has type number, number number 5

Examples 1 ; Number (integer) 3.45 ; Number (real) this is a string ; String (> a b) ; Boolean (cons 1 3) ; Pair<Number, Number> (list 1 2 3) ; List<Number> (cons foo (cons bar nil)) ; List<String> square ; Number Number + ; Number, Number Number string-append ; String, String String 6

Patterns in programming Functions represent commonly occuring patterns: (* (/ (+ a b) 2) (/ (+ c d) 2) (/ (+ e f) 2)) We see (/ (+ x y)) frequently, so we abstract it out into a procedure: (define (average x y) (/ (+ x y))) (* (average a b) (average c d) (average e f)) More efficient, more readable, easier to reuse code, easier to modify code,... 7

More complex patterns (generic programming) 100 k 1 + 2 + + 100 1 + 4 + 9 + + 100 2 1 + 1/3 2 + 1/5 2 + + 1/101 2 (= π 2 /8) (define (sum-integers a b) (if (> a b) 0 (+ a (sum-integers (+ 1 a) b)))) (define (sum-squares a b) (if (> a b) 0 (+ (square a) (sum-squares (+ 1 a) b)))) (define (pi-sum a b) (if (> a b) 0 (+ (/ 1 (square a)) (pi-sum (+ a 2) b)))) (define (sum term a next b) (if (> a b) 0 (+ (term a) k= 1 100 k 2 k= 1 101 k 2 k= 1, odd (sum term (next a) next b)))) 8

Let s examine this new procedure (define (sum term a next b) (if (> a b) 0 (+ (term a) (sum term (next a) next b)))) What is the type of this procedure? (, (, (num num,, num,,, num num, ) num) num 1. What type is the output? 2. How many arguments? 3. What type is each argument? 9

Let s examine this new procedure (define (sum term a next b) (if (> a b) 0 (+ (term a) (sum term (next a) next b)))) What is the type of this procedure? 10

Higher order procedures A higher order procedure: takes a procedure as an argument or returns one as a value (define (sum-integers a b) (if (> a b) 0 (+ a (sum-integers (+ 1 a) b)))) (define (sum term a next b) (if (> a b) 0 (+ (term a)(sum term (next a) next b)))) (define (sum-integers1 a b) (sum ) (lambda (x) x) a (lambda (x) (+ x 1)) b) 11

Higher order procedures (define (sum-squares a b) (if (> a b) 0 (+ (square a) (sum-squares (+ 1 a) b)))) (define (sum term a next b) (if (> a b) 0 (+ (term a)(sum term (next a) next b)))) (define (sum-squares1 a b) (sum square a (lambda (x) (+ x 1)) b)) 12

Higher order procedures (define (pi-sum a b) (if (> a b) 0 (+ (/ 1 (square a)) (pi-sum (+ a 2) b)))) (define (sum term a next b) (if (> a b) 0 (+ (term a)(sum term (next a) next b)))) (define (pi-sum1 a b) (sum (lambda (x) (/ 1 (square x))) a (lambda (x) (+ x 2)) b)) 13

Higher order procedures Take a procedure as an argument, or return one as a value 14

Returning A Procedure As A Value (define (add1 x) (+ x 1)) (define (add2 x) (+ x 2)) (define incrementby (lambda (n)... )) (define add1 (incrementby 1)) (define add2 (incrementby 2))... (define add37.5 (incrementby 37.5)) incrementby: # (# #) (define (sum term a next b) (if (> a b) 0 (+ (term a)(sum term (next a) next b)))) 15

Returning A Procedure As A Value (define incrementby (lambda(n)(lambda (x) (+ x n)))) (incrementby 2) ( (lambda(n)(lambda (x) (+ x n))) 2) (lambda (x) (+ x 2)) (incrementby 2) a procedure of one var (x) that increments x by 2 ((incrementby 3) 4)? ( (lambda(x)(+ x 3)) 4) 16

Returning A Procedure As A Value (define incrementby (lambda(n)(lambda (x) (+ x n)))) (incrementby 2) ( (lambda(n)(lambda (x) (+ x n))) 2) (lambda (x) (+ x 2)) (incrementby 2) ((incrementby 3) 4)? ( (lambda(x)(+ x 3)) 4) TODO: Fix animations 17

Nano-Quiz/Lecture Problem (define incrementby (lambda(n)(lambda (x) (+ x n)))) (define f1 (incrementby 6))? (f1 4) (define f2 (lambda (x)(incrementby 6)))? (f2 4)? ((f2 4) 6)? 18

Procedures as values: Derivatives f:x x 2 f:x x 3 f ': x 2 x f ': x 3 x 2 Taking the derivative is a function: What is its type? D f =f' D:(# # ) (# #) 19

Computing derivatives A good approximation: Df x f x+ε f x (define deriv (lambda (f) (lambda (x) (/ (- (f (+ x epsilon)) (f x)) epsilon)) )) ε (number number) (number number) 20

Using deriv (define square (lambda (y) (* y y)) ) (define epsilon 0.001) (define 2x (deriv square)) (2x 5) (define deriv (lambda (f) (lambda (x) (/ (- (f (+ x epsilon)) (f x)) epsilon)) )) 10.001000000002591 21

Common Pattern #1: Transforming a List (define (square-list lst) (if (null? lst) nil (adjoin (square (first lst)) (square-list (rest lst))))) (define (double-list lst) (if (null? lst) nil (adjoin (* 2 (first lst)) (double-list (rest lst))))) (define (map proc lst) (if (null? lst) nil (adjoin (proc (first lst)) (map proc (rest lst))))) (define (square-list lst) (map square lst)) (square-list (list 1 2 3 4))? (define (double-list lst) (map (lambda (x) (* 2 x)) lst)) Transforms a list to a list, replacing each value by the procedure applied to that value 22

Procedures as arguments: a more complex example (define (compose f g) (lambda (x) (f (g x)))) (define sin_squared (compose square sin)) (define pi/3 1.0471975511965976) (sin_squared pi/3) ==> ((compose square sin) 1.047...) ==> ((lambda (x) (square (sin x))) 1.047...) ==> (square (sin 1.047...)) ===>.749999999999 What is the type of compose? Is it: (number number),(number number) (number number) No! Nothing in compose requires a number 23

Compose works on other types too (define (compose f g) (lambda (x) (f (g x)))) ((compose (lambda (p) (if p "hi" "bye")) (lambda (x) (> x 0)) ) -5 ) ==> "bye" Will any call to compose work? ((compose < square) 5) wrong number of args to < <: number, number boolean ((compose square double) "hi") wrong type of arg to double double: number number boolean string number boolean number result: a string 24

Type of compose (define (compose f g) (lambda (x) (f (g x)))) Use type variables. compose: (B C), (A B) (A C) Meaning of type variables: All places where a given type variable appears must match when you fill in the actual operand types The constraints are: F and G must be functions of one argument the argument type of G matches the type of X the argument type of F matches the result type of G the result type of compose is the result type of F 25

Common Pattern #2: Accumulating Results (define (add-up lst) (if (null? lst) 0 (+ (first lst) (add-up (rest lst))))) (define (mult-all lst) (if (null? lst) 1 (* (first lst) (mult-all (rest lst))))) 26

Common Pattern #2: Accumulating Results (define (accumulate func initial lst) (if (null? lst) initial (func (car lst) (accumulate func initial (cdr lst))) )) (define (add-up lst) (accumulate + 0 lst)) (define (mult-all lst) (accumulate * 1 lst)) (define (add-up lst) (if (null? lst) 0 (+ (first lst) (add-up (rest lst))))) (define (mult-all lst) (if (null? lst) 1 (* (first lst) (mult-all (rest lst))))) 27

Using accumuluate length of a list (accumulate (lambda (x y) (+ y 1)) 0 list) Or, we can also: (define (unary->binary-2 f) (lambda (x y) (f y))) (define (list-length lst) (fold-right (unary->binary-2 (incrementby 1)) 0 lst)) maximum of a list of positive integers (accumulate max 0 (list 1 2 5 6 1 2)) MIT/GNU Scheme provides accumulation functions fold-right fold-left... Check reference manual for details 28

Filtering a list with accumulate (our-keep-matching-items '(1 2 3 4 5 even?) ;Value: (2 4) (define (our-keep-matching-items lst pred?) (fold-right (lambda (x y) (if (pred? x) (cons x y) y)) '() lst) ) 29

Some common higher-order list procedures Filtering (keep-matching-items (list 1 2 3 4) even?) ===> (2 4) (delete-matching-items (list 1 2 3 4) even?) ===> (1 3) Sorting (sort((list 4 8 1) <) ===> (1 4 8) (sort (list 2 5 1 8) (lambda (x y) (even? x))) ===> (8 2 5 1) fold-right/fold-left: Accumulation there-exists: searching Check MIT/GNU Scheme Reference Manual 30

Example f a a+d a+nd n i= 0 f a+iδ =f a +f a+δ +f a+ 2 δ...+f a+nδ 31

Using common patterns over data structures (define (generate-interval a b) (if (> a b) nil (cons a (generate-interval (+ 1 a) b)))) (generate-interval 0 6)? (define (sum f a delta n) (add-up (map (lambda (i) (f (+ a (* i delta)))) (generate-interval 0 n)))) n i= 0 f a+iδ 32

Integration as a procedure Integration under a curve f is given roughly by dx (f(a) + f(a + dx) + f(a + 2dx) + + f(b)) f a dx b (define (integral f a b n) (let ((delta (/ (- b a) n))) (* delta (sum f a delta n)))) 33

Computing Integrals (define (integral f a b n) (let ((delta (/ (- b a) n))) (* (sum f a delta n) delta))) a 0 1 1+x 2 dx=? (define atan (lambda (a) (integral (lambda (x) (/ 1 (+ 1 (square x)))) 0 a))) 34

Higher order procedures Procedures may be passed in as arguments Procedures may be returned as values Procedures may be used as parts of data structures Procedures are first class objects in Scheme!! 35

Fin The end 36

Your turn The following expressions evaluate to values of what type? (lambda (a b c) (if (> a 0) (+ b c) (- b c))) number, number, number (lambda (p) (if p "hi" "bye")) number Boolean (* 3.14 (* 2 5)) string number 37

Your turn The following expressions evaluate to values of what type? (lambda (a b c) (if (> a 0) (+ b c) (- b c))) number, number, number (lambda (p) (if p "hi" "bye")) number Boolean (* 3.14 (* 2 5)) string number 38

Types, precisely A type describes a set of scheme values number number describes the set: all procedures, whose result is a number, that also require one argument that must be a number Every scheme value has a type Some values can be described by multiple types If so, choose the type which describes the largest set Special form keywords like define do not name values therefore special form keywords have no type 39

Type examples expression: 15 number "hi" square evaluates to a value of type: string number number > number,number boolean (> 5 4) ==> #t The type of a procedure is a contract: If the operands have the specified types, the procedure will result in a value of the specified type otherwise, its behavior is undefined maybe an error, maybe random behavior 40

Types (+ 5 10) ==> 15 (+ "hi 5) ;The object "hi", passed as the first argument to integer-add, is not the correct type The type of the integer-add procedure is number, number number two arguments, both numbers Addition is not defined for strings result value of integer-add is a number 41

End of part 1 type: a set of values every value has a type procedure types (types which include ) indicate number of arguments required type of each argument type of result of the procedure Types: a mathematical theory for reasoning efficiently about programs useful for preventing certain common types of errors basis for many analysis and optimization algorithms 42

What is procedure abstraction? Capture a common pattern (* 2 2) (* 57 57) (* k k) (lambda (x) (* x x)) Actual pattern Formal parameter for pattern Give it a name (define square (lambda (x) (* x x))) Note the type: number number 43

Procedures as arguments: a more complex example (define (compose f g) (lambda (x) (f (g x))))(define compose (lambda (f g) (f (g x)))) (compose square double 3) (square (double 3)) (square (* 3 2)) (square 6) (* 6 6) 36 What is the type of compose? Is it: (number number), (number number), number number 44

Compose works on other types too (define compose (lambda (f g x) (f (g x)))) (compose (lambda (p) (if p "hi" "bye")) (lambda (x) (> x 0)) -5 ) ==> "bye" Will any call to compose work? (compose < square 5) boolean string number boolean number result: a string (compose square double "hi") 45

Nano-Quiz/Lecture Problem (define incrementby (lambda(n)(lambda (x) (+ x n)))) (define f1 (incrementby 6))? (define f1 (lambda (x)(incrementby 6)))? 46

Higher order procedures Takes a procedure as an argument or returns one as a value (define (sum-integers1 a b) (sum (lambda (x) x) a (lambda (x) (+ x 1)) b)) (define (sum-squares1 a b) (sum square a (lambda (x) (+ x 1)) b)) (define (add1 x) (+ x 1)) (define (sum-squares1 a b)(sum square a add1 b)) (define (pi-sum1 a b) (sum (lambda (x) (/ 1 (square x))) a (lambda (x) (+ x 2)) b)) (define (add2 x) (+ x 2)) (define (pi-sum1 a b) (sum (lambda (x) (/ 1 (square x))) a add2 b)) 47