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

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

FUNCTIONAL PROGRAMMING

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

CSci 4223 Principles of Programming Languages

Introduction to OCaml

CS 321 Programming Languages

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

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

Functions. Nate Foster Spring 2018

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

CS Lecture 5: Pattern Matching. Prof. Clarkson Fall Today s music: Puff, the Magic Dragon by Peter, Paul & Mary

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

Forward Recursion. Programming Languages and Compilers (CS 421) Mapping Recursion. Forward Recursion: Examples. Folding Recursion.

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

Programming Languages and Compilers (CS 421)

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

CS3110 Spring 2017 Lecture 7 Specifications using types continued

CSCI 2041: First Class Functions

CSCI-GA Scripting Languages

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

CSE341: Programming Languages Lecture 6 Nested Patterns Exceptions Tail Recursion. Zach Tatlock Winter 2018

The Environment Model

Forward recursion. CS 321 Programming Languages. Functions calls and the stack. Functions calls and the stack

CS Lecture 7: The dynamic environment. Prof. Clarkson Spring Today s music: Down to Earth by Peter Gabriel from the WALL-E soundtrack

CS3110 Spring 2016 Lecture 6: Modules

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

SNU Programming Language Theory

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

Programming Languages and Techniques (CIS120)

Lists. Prof. Clarkson Fall Today s music: "Blank Space" by Taylor Swift

CSC324- TUTORIAL 5. Shems Saleh* *Some slides inspired by/based on Afsaneh Fazly s slides

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

List Functions, and Higher-Order Functions

Lecture 4: Higher Order Functions

Programming Languages and Techniques (CIS120)

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

CMSC 330: Organization of Programming Languages. OCaml Expressions and Functions

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

School of Computer Science

Introduction to OCaml

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

CS152: Programming Languages. Lecture 11 STLC Extensions and Related Topics. Dan Grossman Spring 2011

The Substitution Model

An introduction introduction to functional functional programming programming using usin Haskell

CS 440: Programming Languages and Translators, Spring 2019 Mon

Part I: Written Problems

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

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

CS Prof. Clarkson Fall 2014

CS 11 Haskell track: lecture 1

n n Try tutorial on front page to get started! n spring13/ n Stack Overflow!

Racket. CSE341: Programming Languages Lecture 14 Introduction to Racket. Getting started. Racket vs. Scheme. Example.

CSci 4223 Principles of Programming Languages

Programming Languages and Compilers (CS 421)

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

Formal Semantics. Prof. Clarkson Fall Today s music: Down to Earth by Peter Gabriel from the WALL-E soundtrack

Introduction to ML. Mooly Sagiv. Cornell CS 3110 Data Structures and Functional Programming

CSE 341: Programming Languages

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

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

Modular Programming. Prof. Clarkson Fall Today s music: "Giorgio By Moroder" by Daft Punk

INF121: Functional Algorithmic and Programming

Programming Languages and Techniques (CIS120)

Some Advanced ML Features

CSE 130 [Winter 2014] Programming Languages

CMSC 430 Introduction to Compilers. Fall Everything (else) you always wanted to know about OCaml (but were afraid to ask)

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

COSE212: Programming Languages. Lecture 3 Functional Programming in OCaml

CS 11 Ocaml track: lecture 2

Review. CS152: Programming Languages. Lecture 11 STLC Extensions and Related Topics. Let bindings (CBV) Adding Stuff. Booleans and Conditionals

CS 421, Fall Sample Final Questions & Solutions

CMSC330. Objects, Functional Programming, and lambda calculus

To figure this out we need a more precise understanding of how ML works

Programming Languages and Techniques (CIS120)

To figure this out we need a more precise understanding of how ML works

Lab 7: OCaml 12:00 PM, Oct 22, 2017

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

A Third Look At ML. Chapter Nine Modern Programming Languages, 2nd ed. 1

Exercise 1 ( = 24 points)

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

Verification in Coq. Prof. Clarkson Fall Today s music: Check Yo Self by Ice Cube

CSE341 Spring 2016, Midterm Examination April 29, 2016

COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen

Recap: Functions as first-class values

CS-XXX: Graduate Programming Languages. Lecture 9 Simply Typed Lambda Calculus. Dan Grossman 2012

Exercise 1 ( = 22 points)

Functional Programming. Overview. Topics. Definition n-th Fibonacci Number. Graph

CSE341, Fall 2011, Midterm Examination October 31, 2011

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.

Introduction to ML. Mooly Sagiv. Cornell CS 3110 Data Structures and Functional Programming

Programming Languages and Techniques (CIS120)

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

CSE341 Spring 2016, Midterm Examination April 29, 2016

CS152: Programming Languages. Lecture 7 Lambda Calculus. Dan Grossman Spring 2011

Introduction to ML. Mooly Sagiv. Cornell CS 3110 Data Structures and Functional Programming

The Environment Model. Nate Foster Spring 2018

Programming Languages Fall 2014

Exercises on ML. Programming Languages. Chanseok Oh

CSCC24 Functional Programming Scheme Part 2

Transcription:

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

Review Features so far: variables, operators, let expressions, if expressions, functions (higher-order, anonymous), datatypes, records, lists, options, match expressions, type variables Today: Map, fold, and other higher-order functions

Question #1 How much of PS1 have you finished? A. None B. About 25% C. About 50% D. About 75% E. I m done!!!

PS1 PS1 is due tonight at 11:59 pm No extensions Use up a late pass to submit 48 hours late No compile? Zero. Your responsibility to double check your code before submitting We give you a courtesy email if your code doesn t compile We can t guarantee delivery of email Check your email, even spam folder, tomorrow

Review: higher-order functions Functions are values Can use them anywhere we use values Arguments, results, parts of tuples, bound to variables, carried by datatype constructors or exceptions, First-class citizens of language, afforded all the rights of any other values Functions can take functions as arguments Functions can return functions as results functions can be higher-order 5

Review: anonymous functions (aka function expressions) Syntax: fun x -> e really fun p -> e Type checking: Conclude that fun x -> e : ta -> tb if e:tb under assumption x:ta No assumption for function name itself, unlike functions declared with let rec! Evaluation: A function is already a value

Lambda In PL, anonymous functions a.k.a. lambda expressions λx. e The lambda means what follows is an anonymous function x is its argument e is its body Just like fun x -> e, but slightly different syntax Standard feature of any functional language (ML, Haskell, Scheme, ) You ll see lambda show up in many places in PL, e.g.: http://www.php.net/manual/en/function.create-function.php http://lambda-the-ultimate.org/ https://www.youtube.com/watch?v=ci48kqp11f8 7

Review: currying Recall: every OCaml function takes exactly one argument Can encode n arguments with one n-tuple Or, can write function that takes one argument and returns a function that takes another argument and Called currying after famous logician Haskell vs. Curry 8

Haskell B. Curry 1900-1982 Languages Haskell and Curry named for him Curry-Howard isomorphism: Types are logical formulas Programs are logical proofs fun x -> x : a -> a 9

HUGE HIGHER-ORDER FUNCTIONS Discovery of the monolith: https://www.youtube.com/watch?v=ml1ozchixr0

Map bad style! map (fun x -> shirt_color(x)) [ ] = [gold, blue, red] 11

Map map shirt_color [ ] = [gold, blue, red] 12

Map let rec map f xs = match xs with [] -> [] x::xs -> (f x)::(map f xs ) map : ('a -> 'b) -> 'a list -> 'b list Map is HUGE: You use it all the time once you know it Exists in standard library as List.map, but the idea can be used in any data structure (trees, stacks, queues ) 13

Question #2 What is value of lst after this code? let is_even x = (x mod 2 = 0) let lst = map is_even [1;2;3;4] A. [1;2;3;4] B. [2;4] C. [false; true; false; true] D. false

Question #2 What is value of lst after this code? let is_even x = (x mod 2 = 0) let lst = map is_even [1;2;3;4] A. [1;2;3;4] B. [2;4] C. [false; true; false; true] D. false

Filter filter is_vulcan [ ] = [ ] (er, half vulcan) 16

Filter let filter f xs = match xs with [] -> [] x::xs -> if f x then x::(filter f xs ) else filter f xs filter : ('a -> bool) -> 'a list -> 'a list Filter is also HUGE In library: List.filter 17

Question #3 What is value of lst after this code? let is_even x = (x mod 2 = 0) let lst = filter is_even [1;2;3;4] A. [1;2;3;4] B. [2;4] C. [false; true; false; true] D. false

Question #3 What is value of lst after this code? let is_even x = (x mod 2 = 0) let lst = filter is_even [1;2;3;4] A. [1;2;3;4] B. [2;4] C. [false; true; false; true] D. false

Iterators Map and filter are iterators Not built-in to the language, an idiom Benefit of iterators: separate recursive traversal from data processing Can reuse same traversal for different data processing Can reuse same data processing for different data structures leads to modular, maintainable, beautiful code! So far: iterators that change or omit data what about combining data? e.g., sum all elements of list 20

Fold v1.0 Idea: stick an operator between every element of list folding [1;2;3] with (+)! becomes 1+2+3! -->! 6!

Fold v2.0 Idea: stick an operator between every element of list But list could have 1 element, so need an initial value folding [1] with 0 and (+)! becomes 0+1! -->! 1!

Fold v2.0 Idea: stick an operator between every element of list But list could have 1 element, so need an initial value folding [1;2;3] with 0 and (+)! becomes 0+1+2+3! -->! 6!

Fold v2.0 Idea: stick an operator between every element of list But list could have 1 element, so need an initial value Or list could be empty; just return initial value folding [] with 0 and (+)! becomes 0!

Question #4 What should the result of folding [1;2;3;4] with 1 and ( * ) be? A. 1 B. 24 C. 10 D. 0

Question #4 What should the result of folding [1;2;3;4] with 1 and ( * ) be? A. 1 B. 24 C. 10 D. 0

Fold v3.0 Idea: stick an operator between every element of list But list could have 1 element, so need an initial value Or list could be empty; just return initial value Implementation detail: iterate left-to-right or right-to-left? folding [1;2;3] with 0 and (+)! left to right becomes: ((0+1)+2)+3 right to left becomes: 1+(2+(3+0)) Both evaluate to 6; does it matter? Yes: not all operators are associative, e.g. subtraction, division, exponentiation,

Fold v4.0 (+) accumulated a result of the same type as list itself What about operators that change the type? e.g., :: has type a -> a list -> a list! folding from the right [1;2;3] with [] and ::! should produce 1::(2::(3::[])) = [1;2;3]! So the operator needs to accept the accumulated result so far, and the next element of the list which may have different types!

Fold for real Two versions in OCaml library: List.fold_left! : ('a -> 'b -> 'a) -> 'a -> 'b list -> 'a!!! List.fold_right! : ('a -> 'b -> 'b) -> 'a list -> 'b -> 'b!

Fold for real Two versions in OCaml library: List.fold_left! : ('a -> 'b -> 'a) -> 'a -> 'b list -> 'a!!! List.fold_right! : ('a -> 'b -> 'b) -> 'a list -> 'b -> 'b! Operator

Fold for real Two versions in OCaml library: List.fold_left! : ('a -> 'b -> 'a) -> 'a -> 'b list -> 'a!!! List.fold_right! : ('a -> 'b -> 'b) -> 'a list -> 'b -> 'b! Input list

Fold for real Two versions in OCaml library: List.fold_left! : ('a -> 'b -> 'a) -> 'a -> 'b list -> 'a!!! List.fold_right! : ('a -> 'b -> 'b) -> 'a list -> 'b -> 'b! Initial value of accumulator

Fold for real Two versions in OCaml library: List.fold_left! : ('a -> 'b -> 'a) -> 'a -> 'b list -> 'a!!! List.fold_right! : ('a -> 'b -> 'b) -> 'a list -> 'b -> 'b! Final value of accumulator

fold_left! let rec fold_left f acc xs = match xs with [] -> acc x::xs -> fold_left f (f acc x) xs Accumulates an answer by repeatedly applying f to answer so far, starting with initial value acc,! folding from the left fold_left f acc [a;b;c]! computes f (f (f acc a) b) c! 34

fold_right! let rec fold_right f xs acc = match xs with [] -> acc x::xs -> f x (fold_right f xs acc) Accumulates an answer by repeatedly applying f to answer so far, starting with initial value acc,! folding from the right fold_right f [a;b;c] acc! computes f a (f b (f c acc))! 35

Behold the HUGE power of fold Implement so many other functions with fold! let rev xs = fold_left (fun xs x -> x::xs) [] xs let length xs = fold_left (fun a _ -> a+1) 0 xs let map f xs = fold_right (fun x a -> (f x)::a) xs [] let filter f xs = fold_right (fun x a -> if f x then x::a else a) xs [] 36

Beware the efficiency of fold Implementation of fold_left more space efficient than fold_right for long lists But that doesn t mean that one is strictly better than the other More in recitation

Map-Reduce Fold has many synonyms/cousins in various functional languages, including scan and reduce! Google organizes large-scale data-parallel computations with Map-Reduce open source implementation by Apache called Hadoop [Google s Map-Reduce] abstraction is inspired by the map and reduce primitives present in Lisp and many other functional languages. We realized that most of our computations involved applying a map operation to each logical record in our input in order to compute a set of intermediate key/value pairs, and then applying a reduce operation to all the values that shared the same key in order to combine the derived data appropriately." [Dean and Ghemawat, 2008]

Please hold still for 1 more minute WRAP-UP FOR TODAY

Upcoming events PS1 is due tonight at 11:59 pm PS2 will be issued today, due in one week Clarkson office hours today: 2-4 pm This is HUGE THIS IS 3110