Today. Recap from last Week. Factorial. Factorial. How does it execute? How does it execute? More on recursion. Higher-order functions

Similar documents
Factorial. Next. Factorial. How does it execute? Tail recursion. How does it execute? More on recursion. Higher-order functions

Next. Tail Recursion: Factorial. How does it execute? Tail recursion. Tail recursive factorial. Tail recursive factorial.

max function Next concat function max function What s the pattern? concat function More on recursion Higher-order functions

Today s Plan. Programming Languages. Example : Factorial. Recursion. CSE 130 : Spring Lecture 6: Higher-Order Functions

Programming Languages. Tail Recursion. CSE 130: Winter Lecture 8: NOT TR. last thing function does is a recursive call

Recap: Functions as first-class values

Recursion. Q: What does this evaluate to? Q: What does this evaluate to? CSE 130 : Programming Languages. Higher-Order Functions

Write: evens. evens [] ====> [] evens [1;2;3;4] ====> [2;4]

News. CSE 130: Programming Languages. Environments & Closures. Functions are first-class values. Recap: Functions as first-class values

CSE 130 [Winter 2014] Programming Languages

Begin at the beginning

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

CSci 4223 Principles of Programming Languages

CMSC 330, Fall 2013, Practice Problems 3

CMSC 330, Fall 2013, Practice Problem 3 Solutions

CMSC 330: Organization of Programming Languages. OCaml Higher Order Functions

CMSC 330: Organization of Programming Languages. OCaml Higher Order Functions

CMSC 330: Organization of Programming Languages. OCaml Higher Order Functions

Monday Feb 16, 5pm. solve these equalities. Midterm Thursday Feb 12. covers only ocaml part of the course, assignments 1 through 3.

Functional Programming. Pure Functional Programming

Plan (next 4 weeks) 1. Fast forward. 2. Rewind. 3. Slow motion. Rapid introduction to what s in OCaml. Go over the pieces individually

Tuples. CMSC 330: Organization of Programming Languages. Examples With Tuples. Another Example

SCHEME 10 COMPUTER SCIENCE 61A. July 26, Warm Up: Conditional Expressions. 1. What does Scheme print? scm> (if (or #t (/ 1 0)) 1 (/ 1 0))

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

OCaml. ML Flow. Complex types: Lists. Complex types: Lists. The PL for the discerning hacker. All elements must have same type.

Recap from last time. Programming Languages. CSE 130 : Fall Lecture 3: Data Types. Put it together: a filter function

Functions Over Lists. Programming Languages and Compilers (CS 421) Structural Recursion. Functions Over Lists. Structural Recursion : List Example

News. Programming Languages. Complex types: Lists. Recap: ML s Holy Trinity. CSE 130: Spring 2012

Variables and Bindings

Conversion vs. Subtyping. Lecture #23: Conversion and Type Inference. Integer Conversions. Conversions: Implicit vs. Explicit. Object x = "Hello";

Lecture #23: Conversion and Type Inference

Booleans (aka Truth Values) Programming Languages and Compilers (CS 421) Booleans and Short-Circuit Evaluation. Tuples as Values.

CS Lecture 6: Map and Fold. Prof. Clarkson Fall Today s music: Selections from the soundtrack to 2001: A Space Odyssey

CS 312, Fall Exam 1

CMSC330 Spring 2014 Midterm 2 Solutions

Back to OCaml. Summary of polymorphism. Example 1. Type inference. Example 2. Example 2. Subtype. Polymorphic types allow us to reuse code.

CS Lecture 6: Map and Fold. Prof. Clarkson Spring Today s music: Selections from the soundtrack to 2001: A Space Odyssey

OCaml. History, Variants. ML s holy trinity. Interacting with ML. Base type: Integers. Base type: Strings. *Notes from Sorin Lerner at UCSD*

Map and Fold. Prof. Clarkson Fall Today s music: Selections from the soundtrack to 2001: A Space Odyssey

Introduction to OCaml

Programming Languages

Lecture #13: Type Inference and Unification. Typing In the Language ML. Type Inference. Doing Type Inference

# true;; - : bool = true. # false;; - : bool = false 9/10/ // = {s (5, "hi", 3.2), c 4, a 1, b 5} 9/10/2017 4

CSci 4223 Principles of Programming Languages

Programming Languages and Techniques (CIS120)

Programming Languages

Programming Languages

COSE212: Programming Languages. Lecture 4 Recursive and Higher-Order Programming

So what does studying PL buy me?

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

Call-by-name evaluation

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

PROGRAMMING IN HASKELL. CS Chapter 6 - Recursive Functions

Any questions. Say hello to OCaml. Say hello to OCaml. Why readability matters. History, Variants. Plan (next 4 weeks)

Programming Languages

An introduction to Scheme

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

Programming Languages

LECTURE 16. Functional Programming

Programming Languages

Functional Programming. Pure Functional Programming

FUNCTIONAL PROGRAMMING

COP-5555 PROGRAMMING LANGUAGEPRINCIPLES NOTES ON RPAL

Programming Languages

F28PL1 Programming Languages. Lecture 14: Standard ML 4

CMSC330 Fall 2014 Midterm 2 Solutions

Programming Languages

Currying fun f x y = expression;

Lecture 10: Recursion vs Iteration

Programming Languages

The Art of Recursion: Problem Set 10

CS1 Recitation. Week 2

15-451/651: Design & Analysis of Algorithms November 20, 2018 Lecture #23: Closest Pairs last changed: November 13, 2018

Defining Functions. CSc 372. Comparative Programming Languages. 5 : Haskell Function Definitions. Department of Computer Science University of Arizona

INTRODUCTION TO HASKELL

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

RECURSION, RECURSION, (TREE) RECURSION! 2

COSE212: Programming Languages. Lecture 3 Functional Programming in OCaml

A brief tour of history

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

COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen

Informatics 1 Functional Programming Lecture 7. Map, filter, fold. Don Sannella University of Edinburgh

CMSC 330: Organization of Programming Languages. Closures (Implementing Higher Order Functions)

CSE 341 Lecture 5. efficiency issues; tail recursion; print Ullman ; 4.1. slides created by Marty Stepp

Introduction to Functional Programming and Haskell. Aden Seaman

Lists. Michael P. Fourman. February 2, 2010

CSE341, Fall 2011, Midterm Examination October 31, 2011

Chapter 1. Fundamentals of Higher Order Programming

15-451/651: Design & Analysis of Algorithms April 18, 2016 Lecture #25 Closest Pairs last changed: April 18, 2016

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

functional programming in Python, part 2

Recursion. What is Recursion? Simple Example. Repeatedly Reduce the Problem Into Smaller Problems to Solve the Big Problem

CMSC 330: Organization of Programming Languages. Closures (Implementing Higher Order Functions)

Functional Programming

Functional Programming

CS 135 Winter 2018 Tutorial 7: Accumulative Recursion and Binary Trees. CS 135 Winter 2018 Tutorial 7: Accumulative Recursion and Binary Trees 1

Anonymous Functions CMSC 330: Organization of Programming Languages

Functional Programming in C++

Lecture 4: Higher Order Functions

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

Transcription:

Recap from last Week Three key ways to build complex types/values 1. Each-of types Value of T contas value of T1 and a value of T2 2. One-of types Value of T contas value of T1 or a value of T2 Today More on recursion Higher-order functions takg and returng functions 3. Recursive Value of T contas (sub)-value of same type T 1 2 Factorial Factorial let rec fact n = let rec fact n = if n<=0 then 1 else n * fact (n-1);; 3 4 How does it execute? let rec fact n = if n<=0 then 1 else n * fact (n-1);; fac 3;; How does it execute? let rec fact n = if n<=0 then 1 else n * fact (n-1);; fac 3;; 5 6 1

Tail recursion Tail recursion: recursion where all recursive calls are followed by a return other words: not allowed to do any between recursive call and return Tail recursive factorial 7 8 Tail recursive factorial How does it execute? let rec helper x curr = if x <= 0 then curr else helper (x - 1) (x * curr) helper x 1;; let rec helper x curr = if x <= 0 then curr else helper (x - 1) (x * curr) helper x 1;; fact 3;; 9 10 How does it execute? let rec helper x curr = if x <= 0 then curr else helper (x - 1) (x * curr) helper x 1;; fact 3;; Tail recursion Tail recursion: recursion where all recursive calls are followed by a return other words: not allowed to do any between recursive call and return Why do we care about tail recursion? it turns out that tail recursion can be optimized to a simple loop 11 12 2

Compiler can optimize! Tail recursion summary let rec helper x curr = if x <= 0 fact(x) { curr := 1; while (1) { if (x <= 0) Tail recursive calls can be optimized as a jump then curr else helper (x - 1) (x * curr) helper x 1;; } then { return curr } else { x := x 1; curr := (x * curr) } Part of the language specification of some languages (ie: you can count on the compiler to optimize tail recursive calls) recursion! Loop! 13 14 More recursion: terval terval (* return a list that contas the tegers i through j clusive *) let rec terval i j = (* return a list that contas the tegers i through j clusive *) let rec terval i j = if i > j then [] else i::(terval (i+1) j);; 15 16 terval function with it fn terval function with it fn (* return a list that contas the elements f(i), f(i+1),... f(j) *) let rec terval_it i j f = (* return a list that contas the elements f(i), f(i+1),... f(j) *) let rec terval_it i j f = if i > j then [] else (f i)::(terval_it (i+1) j f);; 17 18 3

terval function aga terval function aga (* our regular terval function terms of the one with the it function *) let rec terval i j = (* our regular terval function terms of the one with the it function *) let rec terval i j = terval_it i j (fun x -> x);; 19 20 Interval function yet aga! Function Curryg (* let's change the order of parameters... *) let rec terval_it f i j = if i > j then [] else (f i)::(terval_it f (i+1) j);; (* now can use curryg to get terval function! *) let terval = terval_it (fun x -> x);; 21 In general, these two are equivalent: let f = fun x1 -> -> fun xn -> e let f x1 xn = e Multiple argument functions by returng a function that takes the next argument Named after a person (Haskell Curry) 22 Function Curryg vs tuples Function Curryg vs tuples Tuple version: fn defition let f (x1,,xn) = e fn call f (x1,,xn) Consider the followg: let lt x y = x < y; Curried version: fn defition let f x1 xn = e fn call f x1 xn 23 Could have done: let lt (x,y) = x<y; But then no testers possible In general: Curryg allows you to set just the first n params (where n smaller than the total number of params) 24 4

filter filter (* return a list contag all elements of l for which f returns true *) let rec filter f l = 25 (* return a list contag all elements of l for which f returns true *) let rec filter f l = [] -> [] h::t -> let t' = (filter f t) if (f h) then h::t' else t';; 26 map map (* return the list contag f(e) for each element e of l *) let rec map f l = (* return the list contag f(e) for each element e of l *) let rec map f l = [] -> [] h::t -> (f h)::(map f t);; 27 28 composg functions (f o g) (x) = f(g(x)) (* return a function that given an argument x applies f2 to x and then applies f1 to the result*) let compose f1 f2 = composg functions (f o g) (x) = f(g(x)) (* return a function that given an argument x applies f2 to x and then applies f1 to the result*) let compose f1 f2 = fun x -> (f1 (f2 x));; (* another way of writg it *) let compose f1 f2 x = f1 (f2 x);; 29 30 5

Higher-order functions! Higher-order functions! let map_cr_2 = compose map_cr map_cr;; map_cr_2 (terval (-10) 10);; let map_cr_3 = compose map_cr map_cr_2;; map_cr_3 (terval (-10) 10);; let map_cr_3_pos = compose pos_filer map_cr_3;; map_cr_3_pos (terval (-10) 10);; (compose map_cr_3 pos_filer) (terval (-10) 10);; let map_cr_2 = compose map_cr map_cr;; map_cr_2 (terval (-10) 10);; let map_cr_3 = compose map_cr map_cr_2;; map_cr_3 (terval (-10) 10);; let map_cr_3_pos = compose pos_filer map_cr_3;; map_cr_3_pos (terval (-10) 10);; (compose map_cr_3 pos_filer) (terval (-10) 10);; 31 Instead of manipulatg lists, we are manipulatg the list manipulators! 32 max function max function let max x y = if x < y then y else x;; let max x y = if x < y then y else x;; (* return max element of list l *) let list_max l = 33 (* return max element of list l *) let list_max l = h::t -> helper (max h curr) t helper 0 l;; 34 concat function concat function (* concatenate all strgs a list *) let concat l = (* concatenate all strgs a list *) let concat l = h::t -> helper (curr ^ h) t helper "" l;; 35 36 6

What s the pattern? fold let list_max l = h::t -> helper (max h curr) t helper 0 l;; (* to help us see the pattern: *) let list_max l = h::t -> helper (max h curr) t helper 0 l;; let concat l = h::t -> helper (curr ^ h) t helper "" l;; 37 (* fold, the coolest function there is! *) let rec fold f curr l = 38 fold fold (* fold, the coolest function there is! *) let rec fold f curr l = h::t -> fold f (f h curr) t;; (* fold, the coolest function there is! *) let rec fold f curr l = h::t -> fold f (f h curr) t;; 39 40 Examples of fold Examples of fold let list_max = let list_max = fold max 0;; let concat = let concat = fold (^) "";; let multiplier = let multiplier = fold (*) 1;; 41 42 7

Examples of fold let fact n = multiplier (terval 1 n);; Examples of fold let cons x y = x::y;; let f = fold cons [];; (* same as: let f l = fold cons [] l *) Notice how all the recursion is buried side two functions: terval and fold! 43 44 Examples of fold let cons x y = x::y;; let f = fold cons [];; (* same as: let f l = fold cons [] l *) Benefits of higher-order functions Identify common computation patterns Iterate a function over a set, list, tree Accumulate some value over a collection Pull out (factor) common code: Computation Patterns Re-use many different situations 45 46 Funcs takg/returng funcs Higher-order funcs enable modular code Each part only needs local formation Data Structure Client Uses list Uses meta-functions: map,fold,filter Data Structure Library list Provides meta-functions: map,fold,filter Different way of thkg Free your md -Morpheus Different way of thkg about computation Manipulate the manipulators With locally-dependent funs to traverse, accumulate over (lt h), square etc. lists, trees etc. Without requirg Implement. Meta-functions don t need client details of data structure fo 47 48 8