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

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

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

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

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

Anonymous Functions CMSC 330: Organization of Programming Languages

CMSC 330: Organization of Programming Languages. Functional Programming with Lists

CMSC 330: Organization of Programming Languages. Functional Programming with Lists

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

Introduction to OCaml

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

CMSC 330: Organization of Programming Languages. Lets, Tuples, Records

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

Background. CMSC 330: Organization of Programming Languages. Useful Information on OCaml language. Dialects of ML. ML (Meta Language) Standard ML

Functions. Nate Foster Spring 2018

CMSC330 Fall 2014 Midterm 2 Solutions

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

FUNCTIONAL PROGRAMMING

CMSC 330, Fall 2013, Practice Problem 3 Solutions

CMSC 330: Organization of Programming Languages. OCaml Imperative Programming

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

Data Types. Prof. Clarkson Fall Today s music: Pokémon Theme by Jason Paige

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

CMSC 330: Organization of Programming Languages. OCaml Imperative Programming

CMSC 330, Fall 2013, Practice Problems 3

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

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

Data Types. Guest Lecture: Andrew Myers Spring 2018

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

CMSC 330: Organization of Programming Languages. Lambda Calculus

Dialects of ML. CMSC 330: Organization of Programming Languages. Dialects of ML (cont.) Features of ML. Functional Languages. Features of ML (cont.

CSc 372, Fall 2006; Quiz 1 Time: 3:00; Value: 2 points. 1. What is a fundamental difference between the if-then-else constructs in Java (or C) and ML?

CMSC330 Spring 2014 Midterm 2 Solutions

INF121: Functional Algorithmic and Programming

CMSC 330: Organization of Programming Languages. Lambda Calculus

The Substitution Model

CMSC 330: Organization of Programming Languages. Objects and Functional Programming

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

CMSC 330: Organization of Programming Languages

CMSC 330: Organization of Programming Languages. Formal Semantics of a Prog. Lang. Specifying Syntax, Semantics

CMSC 330: Organization of Programming Languages

CSE 130 [Winter 2014] Programming Languages

The Substitution Model. Nate Foster Spring 2018

CMSC 330: Organization of Programming Languages

CMSC 330: Organization of Programming Languages. OCaml Data Types

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

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

CS 321 Programming Languages

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

CMSC 330: Organization of Programming Languages

CIS 120 Midterm I February 16, 2015 SOLUTIONS

CMSC 330, Fall 2018 Midterm 1

Case by Case. Chapter 3

CSE 341: Programming Languages

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

CMSC 330: Organization of Programming Languages

CMSC330. Objects, Functional Programming, and lambda calculus

CMSC 631. Functional Programming with OCaml

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

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

Programming Languages and Techniques (CIS120)

Closures. Mooly Sagiv. Michael Clarkson, Cornell CS 3110 Data Structures and Functional Programming

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

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

CS 135 Fall 2018 Final Exam Review. CS 135 Fall 2018 Final Exam Review 1

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

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

Lecture Outline. COOL operational semantics. Operational Semantics of Cool. Motivation. Lecture 13. Notation. The rules. Evaluation Rules So Far

CMSC 330, Fall 2018 Midterm 1

CSCI-GA Scripting Languages

Operational Semantics of Cool

Closures. Mooly Sagiv. Michael Clarkson, Cornell CS 3110 Data Structures and Functional Programming

CMSC330 Spring 2014 Midterm #2. Score 1 OCaml types & type

Operational Semantics of Cool

Tail Calls. CMSC 330: Organization of Programming Languages. Tail Recursion. Tail Recursion (cont d) Names and Binding. Tail Recursion (cont d)

Functional abstraction. What is abstraction? Eating apples. Readings: HtDP, sections Language level: Intermediate Student With Lambda

Functional abstraction

CMSC 330: Organization of Programming Languages. Rust Basics

OCaml Language Choices CMSC 330: Organization of Programming Languages

The Environment Model

Fall Lecture 3 September 4. Stephen Brookes

Programming Languages and Techniques (CIS120)

List Functions, and Higher-Order Functions

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

COSE212: Programming Languages. Lecture 3 Functional Programming in OCaml

CMSC330 Fall 2015 Midterm #1 12:30pm/2:00pm/5:00pm

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

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

Introduction to Concepts in Functional Programming. CS16: Introduction to Data Structures & Algorithms Spring 2017

CMSC330 Spring 2015 Final Exam 9:30am/11:00am/12:30pm

List Processing in Ocaml

The syntax and semantics of Beginning Student

The syntax and semantics of Beginning Student

CMSC 330: Organization of Programming Languages. Operational Semantics

CSCI 2041: First Class Functions

CSE 130 [Winter 2014] Programming Languages

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

Fall Recursion and induction. Stephen Brookes. Lecture 4

Lecture Outline. COOL operational semantics. Operational Semantics of Cool. Motivation. Notation. The rules. Evaluation Rules So Far.

Operational Semantics. One-Slide Summary. Lecture Outline

CMSC330 Fall 2010 Final Exam Solutions

Transcription:

CMSC 330: Organization of Programming Languages OCaml Higher Order Functions CMSC330 Fall 2017 1

Anonymous Functions Recall code blocks in Ruby (1..10).each { x print x } Here, we can think of { x print x } as a function We can do this (and more) in OCaml 2

Anonymous Functions Passing functions around is very common So often we don t want to bother to give them names Use fun to make a function with no name Parameter Body fun x -> x + 3 (fun x -> x + 3) 5 = 8 3

Anonymous Functions Syntax fun x1 xn -> e Evaluation An anonymous function is an expression In fact, it is a value no further evaluation is possible Ø As such, it can be passed to other functions, returned from them, stored in a variable, etc. Type checking (fun x1 xn -> e ) : (t1 -> -> tn -> u) if e : u under assumptions x1 : t1,, xn : tn. Ø (Same rule as let f x1 xn = e) 4

All Functions Are Anonymous Functions are first-class, so you can bind them to other names as you like let f x = x + 3;; let g = f;; g 5 In fact, let for functions is syntactic shorthand let f x = body = 8 is semantically equivalent to let f = fun x -> body 5

Example Shorthands let next x = x + 1 Short for let next = fun x -> x + 1 let plus x y = x + y Short for let plus = fun x y -> x + y let rec fact n = if n = 0 then 1 else n * fact (n-1) Short for let rec fact = fun n -> (if n = 0 then 1 else n * fact (n-1)) 6

Defining Functions Everywhere let move l x = let left x = x 1 in (* locally defined fun *) let right x = x + 1 in (* locally defined fun *) if l then left x else right x ;; let move l x = (* equivalent to the above *) if l then (fun y -> y 1) x else (fun y -> y + 1) x 7

Calling Functions, Generalized Syntax e0 e1 en Evaluation Evaluate arguments e1 en to values v1 vn Ø Order is actually right to left, not left to right Not just a variable f Ø But this doesn t matter if e1 en don t have side effects Evaluate e0 to a function fun x1 xn -> e Substitute vi for xi in e, yielding new expression e Evaluate e to value v, which is the final result 8

Calling Functions, Generalized Syntax e0 e1 en Type checking (almost the same as before) If e0 : t1 -> -> tn -> u and e1 : t1,, en : tn then e0 e1 en : u Example: (fun x -> x+1) 1 : int since (fun x -> x+1): int -> int and 1 : int 9

Pattern Matching With Fun match can be used within fun (fun l -> match l with (h::_) -> h) [1; 2] = 1 But use named functions for complicated matches May use standard pattern matching abbreviations (fun (x, y) -> x+y) (1,2) = 3 10

Passing Functions as Arguments In OCaml you can pass functions as arguments (akin to Ruby code blocks) let plus_three x = x + 3 (* int -> int *) let twice f z = f (f z) (* ('a->'a) -> 'a -> 'a *) twice plus_three 5 = 11 Ruby s collect is called map in OCaml map f l applies function f to each element of l, and puts the results in a new list (preserving order) map plus_three [1; 2; 3] = [4; 5; 6] map (fun x -> (-x)) [1; 2; 3] = [-1; -2; -3] 11

The Map Function Let s write the map function Takes a function and a list, applies the function to each element of the list, and returns a list of the results let rec map f l = match l with [] -> [] (h::t) -> (f h)::(map f t) let add_one x = x + 1 let negate x = -x map add_one [1; 2; 3] = [2; 3; 4] map negate [9; -5; 0] = [-9; 5; 0] Type of map? 12

The Map Function (cont.) What is the type of the map function? let rec map f l = match l with [] -> [] (h::t) -> (f h)::(map f t) ('a -> 'b) -> 'a list -> 'b list f l 13

The Fold Function This is the fold_left function in OCaml s standard List library Common pattern Iterate through list and apply function to each element, keeping track of partial results computed so far let rec fold f a l = match l with [] -> a (h::t) -> fold f (f a h) t a = accumulator Usually called fold left to remind us that f takes the accumulator as its first argument What's the type of fold? = ('a -> 'b -> 'a) -> 'a -> 'b list -> 'a 14

Example let rec fold f a l = match l with [] -> a (h::t) -> fold f (f a h) t let add a x = a + x fold add 0 [1; 2; 3; 4] fold add 1 [2; 3; 4] fold add 3 [3; 4] fold add 6 [4] fold add 10 [] 10 We just built the sum function! 15

Another Example let rec fold f a l = match l with [] -> a (h::t) -> fold f (f a h) t let next a _ = a + 1 fold next 0 [2; 3; 4; 5] fold next 1 [3; 4; 5] fold next 2 [4; 5] fold next 3 [5] fold next 4 [] 4 We just built the length function! 16

Using Fold to Build Reverse let rec fold f a l = match l with [] -> a (h::t) -> fold f (f a h) t Let s build the reverse function with fold! let prepend a x = x::a fold prepend [] [1; 2; 3; 4] fold prepend [1] [2; 3; 4] fold prepend [2; 1] [3; 4] fold prepend [3; 2; 1] [4] fold prepend [4; 3; 2; 1] [] [4; 3; 2; 1] 17

Summary map f [v1; v2; ; vn] = [f v1; f v2; ; f vn] e.g., map (fun x -> x+1) [1;2;3] = [2;3;4] fold f v [v1; v2; ; vn] = fold f (f v v1) [v2; ; vn] = fold f (f (f v v1) v2) [ ; vn] = = f (f (f (f v v1) v2) ) vn e.g., fold add 0 [1;2;3;4] = add (add (add (add 0 1) 2) 3) 4 = 10 18

Quiz 1: What does this evaluate to? let id x = x in (fun f y -> f (y+1)) id 1 A. Error B. 2 C. 1 D. (id 2) 19

Quiz 1: What does this evaluate to? let id x = x in (fun f y -> f (y+1)) id 1 A. Error B. 2 C. 1 D. (id 2) 20

Quiz 2: What does this evaluate to? map (fun x -> x *. 4) [1;2;3] A. [ 1.0; 2.0; 3.0 ] B. [ 4.0; 8.0; 12.0 ] C. Error D. [4; 8; 12 ] 21

Quiz 2: What does this evaluate to? map (fun x -> x *. 4) [1;2;3] A. [ 1.0; 2.0; 3.0 ] B. [ 4.0; 8.0; 12.0 ] C. Error D. [4; 8; 12 ] 22

Quiz 3: What does this evaluate to? fold (fun a y -> y::a) [] [2;3;4] A. [ 9 ] B. [ 2;5;9 ] C. [ 4;3;2 ] D. Error 23

Quiz 3: What does this evaluate to? fold (fun a y -> y::a) [] [2;3;4] A. [ 9 ] B. [ 2;5;9 ] C. [ 4;3;2 ] D. Error 24

Quiz 4: What does this evaluate to? let is_even x = (x mod 2 = 0) in map is_even [1;2;3;4;5] A. [false;true;false;true;false] B. [0;1;1;2;2] C. [0;0;0;0;0] D. false 25

Quiz 4: What does this evaluate to? let is_even x = (x mod 2 = 0) in map is_even [1;2;3;4;5] A. [false;true;false;true;false] B. [0;1;1;2;2] C. [0;0;0;0;0] D. false 26