max function Next concat function max function What s the pattern? concat function 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.

Today. Recap from last Week. Factorial. Factorial. How does it execute? How does it execute? 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

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

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

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

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

CSE 130 [Winter 2014] Programming Languages

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

CMSC 330, Fall 2013, Practice Problems 3

CMSC 330, Fall 2013, Practice Problem 3 Solutions

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

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

CSci 4223 Principles of Programming Languages

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

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

CSE341 Section 3. Standard-Library Docs, First-Class Functions, & More

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

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

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

INF121: Functional Algorithmic and Programming

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

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

Functional Programming. Pure Functional Programming

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

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

FUNCTIONAL PROGRAMMING

CS 321 Programming Languages

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

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

CSCI 2041: First Class Functions

Currying fun f x y = expression;

CMSC330 Spring 2014 Midterm 2 Solutions

Programming Languages and Compilers (CS 421)

Introduction to OCaml

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

CMSC330 Fall 2014 Midterm 2 Solutions

CS1102: Macros and Recursion

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

Lecture #23: Conversion and Type Inference

CS1 Recitation. Week 2

So what does studying PL buy me?

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

Streams and Evalutation Strategies

Playing with Fun. Walter Cazzola. Playing with Fun currying partial evaluation map&reduce iteration var args. References.

Redefinition of an identifier is OK, but this is redefinition not assignment; Thus

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

A brief tour of history

F# - LISTS. In this method, you just specify a semicolon-delimited sequence of values in square brackets. For example

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

CSCI-GA Scripting Languages

Haske k ll An introduction to Functional functional programming using Haskell Purely Lazy Example: QuickSort in Java Example: QuickSort in Haskell

F28PL1 Programming Languages. Lecture 14: Standard ML 4

List Functions, and Higher-Order Functions

Gain familiarity and practice with folding and mapping. The following supplementary materials may be helpful in completing this assignment:

CS115 - Module 9 - filter, map, and friends

An introduction introduction to functional functional programming programming using usin Haskell

Programming Languages and Techniques (CIS120)

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

Functional Programming

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

Programming Languages

Homework 5. Notes. Turn-In Instructions. Reading. Problems. Handout 19 CSCI 334: Spring (Required) Read Mitchell, Chapters 6 and 7.

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

Functional Programming in Haskell Part I : Basics

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

Lists. Michael P. Fourman. February 2, 2010

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

Lecture 4: Higher Order Functions

Exercises on ML. Programming Languages. Chanseok Oh

A quick introduction to SML

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

ML Built-in Functions

CMSC330 Fall 2016 Midterm #1 2:00pm/3:30pm

Functional Programming

CSE 130 [Winter 2014] Programming Languages

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

CSE 341 : Programming Languages

Programming Languages

Begin at the beginning

CSC/MAT-220: Lab 6. Due: 11/26/2018

Anonymous Functions CMSC 330: Organization of Programming Languages

CSE 130, Winter 2011: Final Examination

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

Programming Languages

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

Module 8: Local and functional abstraction

L3 Programming September 19, OCaml Cheatsheet

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

Case by Case. Chapter 3

Programming Languages

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

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

CSE341: Programming Languages Lecture 9 Function-Closure Idioms. Dan Grossman Fall 2011

PROGRAMMING IN HASKELL. CS Chapter 6 - Recursive Functions

Transcription:

Next More on recursion Higher-order functions taking and returning functions max function let max x y = if x < y then y else x;; (* return max element of list l *) Along the way, will see map and fold 1 2 max function concat function let max x y = if x < y then y else x;; (* return max element of list l *) h::t -> helper (max h curr) t in helper 0 l;; 3 (* concatenate all strings in a list *) let concat l = 4 concat function What s the pattern? (* concatenate all strings in a list *) let concat l = h::t -> helper (curr ^ h) t in helper "" l;; 5 h::t -> helper (max h curr) t in helper 0 l;; let concat l = h::t -> helper (curr ^ h) t in helper "" l;; 6 1

fold, the general helper func! (* to help us see the pattern: *) h::t -> helper (max h curr) t in helper 0 l;; 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 = 7 8 fold (* fold, the coolest function there is! *) let rec fold f curr l = h::t -> fold f (f h curr) t;; let list_max = let concat = let multiplier = 9 10 let list_max = fold max 0;; let concat = fold (^) "";; let fact n = multiplier (interval 1 n);; Notice how all the recursion is buried inside two functions: interval and fold! let multiplier = fold (*) 1;; 11 12 2

let cons x y = x::y;; let f = fold cons [];; (* same as: let f l = fold cons [] l *) let cons x y = x::y;; let f = fold cons [];; (* same as: let f l = fold cons [] l *) 13 14 More recursion: interval interval (* return a list that contains the integers i through j inclusive *) (* return a list that contains the integers i through j inclusive *) if i > j then [] else i::(interval (i+1) j);; 15 16 interval function with init fn interval function with init fn (* return a list that contains the elements f(i), f(i+1),... f(j) *) let rec interval_init i j f = (* return a list that contains the elements f(i), f(i+1),... f(j) *) let rec interval_init i j f = if i > j then [] else (f i)::(interval_init (i+1) j f);; 17 18 3

interval function again interval function again (* our regular interval function in terms of the one with the init function *) (* our regular interval function in terms of the one with the init function *) interval_init i j (fun x -> x);; 19 20 Interval function yet again! Function Currying (* let's change the order of parameters... *) let rec interval_init f i j = if i > j then [] else (f i)::(interval_init f (i+1) j);; (* now can use currying to get interval function! *) let interval = interval_init (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 returning a function that takes the next argument Named after a person (Haskell Curry) 22 Function Currying vs tuples Function Currying vs tuples Tuple version: fn definition let f (x1,,xn) = e fn call f (x1,,xn) Consider the following: let lt x y = x < y; Curried version: fn definition 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: Currying allows you to set just the first n params (where n smaller than the total number of params) 24 4

map map (* return the list containing f(e) for each element e of l *) let rec map f l = (* return the list containing f(e) for each element e of l *) let rec map f l = [] -> [] h::t -> (f h)::(map f t);; 25 26 map let incr x = x+1;; let map_incr = map incr;; map_incr (interval (-10) 10);; composing 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 = 27 28 composing 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 writing it *) let compose f1 f2 x = f1 (f2 x);; Higher-order functions! let map_incr_2 = compose map_incr map_incr;; map_incr_2 (interval (-10) 10);; let map_incr_3 = compose map_incr map_incr_2;; map_incr_3 (interval (-10) 10);; let map_incr_3_pos = compose pos_filer map_incr_3;; map_incr_3_pos (interval (-10) 10);; (compose map_incr_3 pos_filer) (interval (-10) 10);; 29 30 5

Higher-order functions! Exercise 1 let map_incr_2 = compose map_incr map_incr;; map_incr_2 (interval (-10) 10);; let map_incr_3 = compose map_incr map_incr_2;; map_incr_3 (interval (-10) 10);; let map_incr_3_pos = compose pos_filer map_incr_3;; map_incr_3_pos (interval (-10) 10);; (compose map_incr_3 pos_filer) (interval (-10) 10);; Instead of manipulating lists, we are let rec filter f l = [] -> [] h::t -> let t = filter f t in if f h then h::t else t let neg f x = not (f x) let partition f l = (filter f l, filter (neg f) l) This implementation is not ideal, since it unnecessarily processes the list twice. Rewrite partition so that it is a single call to fold_left, so the input list is processed only once. Recall: manipulating the list manipulators! 31 32 Exercise 1 let partition f l = Exercise 1 Solution let partition f l = let fold_fn (pass,passnot) x = if f x then (pass@[x], passnot) else (pass, passnot@[x]) in List.fold_left fold_fn ([],[]) l;; 33 34 Exercise 2 val map : ('a -> 'b) -> 'a list -> 'b list Exercise 2 Solution val map : ('a -> 'b) -> 'a list -> 'b list Implement map using fold: let map f l = Implement map using fold: let map f l = List.fold_left (fun acc x -> acc@[f x]) [] l 35 36 6

Benefits of higher-order functions Identify common computation patterns Iterate a function over a set, list, tree Accumulate some value over a collection Funcs taking/returning funcs Higher-order funcs enable modular code Each part only needs local information Data Structure Client Uses list Data Structure Library list Pull out (factor) common code: Computation Patterns Re-use in many different situations 37 Uses meta-functions: map,fold,filter With locally-dependent funs (lt h), square etc. Without requiring Implement. details of data structure Provides meta-functions: map,fold,filter to traverse, accumulate over lists, trees etc. Meta-functions don t need client info 38 Different way of thinking Free your mind -Morpheus Different way of thinking about computation Manipulate the manipulators 39 7