CMSC 330: Organization of Programming Languages Maps and Folds Anonymous Functions.

Slides:



Advertisements
Similar presentations
Programovací jazyky F# a OCaml Chapter 4. Generic and recursive types.
Advertisements

Introduction to OCaml Slides prepared by Matt Gruskin Some material borrowed from the CIS 500 lecture notes.
Higher-order functions in OCaml. Higher-order functions A first-order function is one whose parameters and result are all "data" A second-order function.
CMSC 330: Organization of Programming Languages Tuples, Types, Conditionals and Recursion or “How many different OCaml topics can we cover in a single.
C. Varela; Adapted w/permission from S. Haridi and P. Van Roy1 Declarative Programming Techniques Accumulators, Difference Lists (VRH ) Carlos Varela.
ML Lists.1 Standard ML Lists. ML Lists.2 Lists  A list is a finite sequence of elements. [3,5,9] ["a", "list" ] []  ML lists are immutable.  Elements.
LING 388: Language and Computers Sandiway Fong Lecture 5: 9/8.
1 Programming Languages (CS 550) Lecture Summary Functional Programming and Operational Semantics for Scheme Jeremy R. Johnson.
Comp 205: Comparative Programming Languages Higher-Order Functions Functions of functions Higher-order functions on lists Reuse Lecture notes, exercises,
ML: a quasi-functional language with strong typing Conventional syntax: - val x = 5; (*user input *) val x = 5: int (*system response*) - fun len lis =
CSE341: Programming Languages Lecture 6 Tail Recursion, Accumulators, Exceptions Dan Grossman Fall 2011.
CSE341: Programming Languages Lecture 8 Lexical Scope and Function Closures Dan Grossman Fall 2011.
0 PROGRAMMING IN HASKELL Chapter 7 - Higher-Order Functions.
ML: a quasi-functional language with strong typing Conventional syntax: - val x = 5; (*user input *) val x = 5: int (*system response*) - fun len lis =
Introduction to ML - Part 2 Kenny Zhu. What is next? ML has a rich set of structured values Tuples: (17, true, “stuff”) Records: {name = “george”, age.
Introduction to ML Last time: Basics: integers, Booleans, tuples,... simple functions introduction to data types This time, we continue writing an evaluator.
CSE 130 : Winter 2006 Programming Languages Ranjit Jhala UC San Diego Lecture 6: Higher-Order Functions, Polymorphism.
CSE 130 : Winter 2006 Programming Languages Ranjit Jhala UC San Diego Lecture 7: Polymorphism.
7/2/20151 Programming Languages and Compilers (CS 421) Elsa L Gunter 2112 SC, UIUC Based in part on slides by Mattox.
Programovací jazyky F# a OCaml Chapter 5. Hiding recursion using function-as-values.
CS 326 Programming Languages, Concepts and Implementation Instructor: Mircea Nicolescu Lecture 7.
Patterns in OCaml functions. Formal vs. actual parameters Here's a function definition (in C): –int add (int x, int y) { return x + y; } –x and y are.
Functional Programming With examples in F#. Pure Functional Programming Functional programming involves evaluating expressions rather than executing commands.
1-Nov-15 Haskell II Functions and patterns. Data Types Int + - * / ^ even odd Float + - * / ^ sin cos pi truncate Char ord chr isSpace isUpper … Bool.
Going Functional Primož Gabrijelčič. Functional programming.
A Second Look At ML 1. Outline Patterns Local variable definitions A sorting example 2.
A Third Look At ML Chapter NineModern Programming Languages, 2nd ed.1.
Lee CSCE 314 TAMU 1 CSCE 314 Programming Languages Haskell: Higher-order Functions Dr. Hyunyoung Lee.
CMSC 330: Organization of Programming Languages Functional Programming with OCaml.
CMSC 330: Organization of Programming Languages
CMSC 330: Organization of Programming Languages Operational Semantics a.k.a. “WTF is Project 4, Part 3?”
CSE 130 : Spring 2011 Programming Languages Ranjit Jhala UC San Diego Lecture 6: Higher-Order Functions.
Kyung-Goo Doh Hanyang University - ERICAComputer Science & Engineering Functional Programming / Imperative Programming CSE215 Fundamentals of Program Design.
Chapter SevenModern Programming Languages1 A Second Look At ML.
CSE 341 : Programming Languages Lecture 8 First Class Functions Zach Tatlock Spring 2014.
CMSC 330: Organization of Programming Languages Operational Semantics.
3/8/20161 Programming Languages and Compilers (CS 421) Reza Zamani Based in part on slides by Mattox Beckman, as updated.
Haskell Chapter 5, Part II. Topics  Review/More Higher Order Functions  Lambda functions  Folds.
CSE 341 : Programming Languages Lecture 9 Lexical Scope, Closures Zach Tatlock Spring 2014.
1.SML Docs Standard Basis 2.First-Class Functions Anonymous Style Points Higher-Order 3.Examples Agenda.
Cs7120 (Prasad)L1-FP-HOF1 Functional Programming Basics Correctness > Clarity > Efficiency.
1 Objective Caml (Ocaml) Aaron Bloomfield CS 415 Fall 2005.
Cs776 (Prasad)L2HOF1 Higher-Order Functions. cs776 (Prasad)L2HOF2 Higher-Order Functions A function that takes a function as argument and/or returns a.
Spring 16 CSCI 4430, A Milanova/BG Ryder 1 Announcements HW5 due March 28 Homework Server link is up I will have office hours, Fri or Mon, check Announcements.
6-Jul-16 Haskell II Functions and patterns. Data Types Int + - * / ^ even odd Float + - * / ^ sin cos pi truncate Char ord chr isSpace isUpper … Bool.
10/1/20161 Programming Languages and Compilers (CS 421) Elsa L Gunter 2112 SC, UIUC Based in part on slides by Mattox.
CSE-321 Programming Languages Introduction to Functional Programming POSTECH 박성우.
Programming Languages and Compilers (CS 421)
Types CSCE 314 Spring 2016.
Programming Languages and Compilers (CS 421)
Functions and patterns
Expanded Recursive Diagrams OCAML rapid tour, day 2
CMSC 330: Organization of Programming Languages
Programming Languages and Compilers (CS 421)
CSE341: Programming Languages Lecture 8 Lexical Scope and Function Closures Dan Grossman Winter 2013.
CSE341: Programming Languages Lecture 8 Lexical Scope and Function Closures Dan Grossman Spring 2013.
Objective caml Daniel Jackson MIT Lab for Computer Science 6898: Advanced Topics in Software Design March 18, 2002.
CSE341: Programming Languages Lecture 8 Lexical Scope and Function Closures Dan Grossman Spring 2016.
CSE341: Programming Languages Lecture 8 Lexical Scope and Function Closures Dan Grossman Autumn 2018.
CSE341: Programming Languages Section 3 Function Patterns Tail Recursion Winter 2018.
CSE341: Programming Languages Lecture 8 Lexical Scope and Function Closures Zach Tatlock Winter 2018.
CSE-321 Programming Languages Introduction to Functional Programming
Madhusudan Parthasarathy
Announcements Quiz 5 HW6 due October 23
Functions and patterns
CSE341: Programming Languages Lecture 8 Lexical Scope and Function Closures Dan Grossman Autumn 2017.
CSE341: Programming Languages Lecture 8 Lexical Scope and Function Closures Dan Grossman Spring 2019.
CS 5010 Program Design Paradigms “Bootcamp” Lesson 4.1
Brett Wortzman Summer 2019 Slides originally created by Dan Grossman
Review Previously in: Lots of language features: functions, lists, records, tuples, variants, pattern matching Today: No new language features New idioms.
Presentation transcript:

CMSC 330: Organization of Programming Languages Maps and Folds Anonymous Functions

Project 3 and Project 4 You may use the List module –There is a link on the “Resources” page –For exams, however, you should be able to implement any of the functions in List With the exception of the sorting functions You may also use the Char, String, Printf and Scanf modules –Make sure your output matches the project spec! You may NOT use the Array or Hashtbl modules –Or any other modules not mentioned here CMSC 330

3 Review sum l (* sum of elts in l *) let rec sum l = match l with [] -> 0 | (x::xs) -> x + (sum xs) negate l (* negate elements in list *) let rec negate l = match l with [] -> [] | (x::xs) -> (-x) :: (negate xs) last l (* last element of l *) let rec last l = match l with [x] -> x | (x::xs) -> last xs

CMSC 3304 Recursion Exercises (cont'd) (* return a list containing all the elements in the list l followed by all the elements in list m *) append (l, m) rev l (* reverse list; hint: use append *) rev takes O(n 2 ) time. Can you do better?

CMSC 3305 Recursion Exercises (cont'd) (* return a list containing all the elements in the list l followed by all the elements in list m *) append (l, m) let rec append (l, m) = match l with [] -> m | (x::xs) -> x::(append (xs, m)) rev l (* reverse list; hint: use append *) let rec rev l = match l with [] -> [] | (x::xs) -> append ((rev xs), [x]) rev takes O(n 2 ) time. Can you do better?

CMSC 3306 A Clever Version of Reverse let rec rev_helper (l, a) = match l with [] -> a | (x::xs) -> rev_helper (xs, (x::a)) let rev l = rev_helper (l, []) Let’s give it a try rev [1; 2; 3] → rev_helper ([1;2;3], []) → rev_helper ([2;3], [1]) → rev_helper ([3], [2;1]) → rev_helper ([], [3;2;1]) → [3;2;1]

CMSC 3307 More Examples flattenPairs l (* ('a * 'a) list -> 'a list *) take (n, l) (* return first n elts of l *)

CMSC 3308 More Examples flattenPairs l (* ('a * 'a) list -> 'a list *) let rec flattenPairs l = match l with [] -> [] | ((a, b)::t) -> a :: b :: (flattenPairs t) take (n, l) (* return first n elts of l *) let rec take (n, l) = if n = 0 then [] else match l with [] -> [] | (x::xs) -> x :: (take (n-1, xs))

CMSC 3309 Working with Lists Several of these examples have the same flavor –Walk through the list and do something to every element –Walk through the list and keep track of something Wouldn’t it be nice to have a generic way of doing this?

CMSC Higher-Order Functions In OCaml you can pass functions as arguments, and return functions as results let plus_three x = x + 3 let twice (f, z) = f (f z) twice (plus_three, 5) (* returns 11 *) twice : ('a->'a) * 'a -> 'a

CMSC 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 add_one x = x + 1 let negate x = -x map (add_one, [1; 2; 3]) map (negate, [9; -5; 0]) Type of map ? let rec map (f, l) = match l with [] -> [] | (h::t) -> (f h)::(map (f, t)) map : ('a -> 'b) * 'a list -> 'b list

CMSC Anonymous Functions Passing functions around is very common –Often we don’t want to bother to give them names Use fun to make a function with no name map ((fun x -> x + 13), [1; 2; 3]) twice ((fun x -> x + 2), 4) fun x -> x + 3 ParameterBody

CMSC Pattern Matching with fun match can be used within fun map ((fun l -> match l with (h::_) -> h), [ [1; 2; 3]; [4; 5; 6; 7]; [8; 9] ]) (* [1; 4; 8] *) –For complicated matches, though, use named functions Standard pattern matching abbreviation can be used map ((fun (x, y) -> x + y), [(1, 2); (3, 4)]) (* [3; 7] *)

CMSC Function Binding 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 (* returns 8 *) let for functions is just a shorthand –let f x = x + 3 stands for –let f = fun x -> x + 3 – Punchline: all functions are anonymous!

CMSC Examples 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 –Which is short for let plus = fun z -> (match z with (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))

CMSC let rec fold (f, a, l) = match l with [] -> a | (h::t) -> fold (f, f (a, h), t) The fold Function Common pattern: iterate through a list and apply a function to each element, keeping track of the partial results computed so far –a = “accumulator” –this is usually called “fold left” to remind us that f takes the accumulator as its first argument What's the type of fold? fold : ('a * 'b -> 'a) * 'a * 'b list -> 'a

CMSC The fold Function What if f took the accumulator as the second argument instead of the first? –This is called “fold right” –It is not tail-recursive, so it is slower than “fold left” let rec fold_right (f, a, l) = match l with [] -> a | (h::t) -> f (h, fold_right (f, a, t))

CMSC Example 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! let rec fold (f, a, l) = match l with [] -> a | (h::t) -> fold (f, f (a, h), t)

CMSC Another Example 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! let rec fold (f, a, l) = match l with [] -> a | (h::t) -> fold (f, f (a, h), t)

CMSC Using fold to Build rev Can you 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] let rec fold (f, a, l) = match l with [] -> a | (h::t) -> fold (f, f (a, h), t)

Basic Partial Evaluation Partial evaluation is the process of consuming multiple inputs by creating temporary anonymous functions let add a b = a + b add 3 4 = (add 3) 4 = (fun x -> 3 + x) 4 = = 7 CMSC 330

Basic Partial Evaluation Each input causes a partial evaluation This is also called “currying” Actually, it creates a slightly more complex structure than just an anonymous function These structures are called “closures” We’ll talk more about this next week CMSC 330