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

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

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

CSE 130 [Winter 2014] Programming Languages

Programming Languages

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

Programming Languages

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

Programming Languages

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

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

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.

Programming Languages

Programming Languages

Programming Languages

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

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 Programming Languages. Lecture 3: Datatypes. Ranjit Jhala UC San Diego

Programming Languages. Example 5. Example 4. CSE 130 : Fall type, can reuse code for all types! let rec cat l = match l with

Recap: ML s Holy Trinity. Story So Far... CSE 130 Programming Languages. Datatypes. A function is a value! Next: functions, but remember.

CSE 130 Programming Languages. Datatypes. Ranjit Jhala UC San Diego

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

FUNCTIONAL PROGRAMMING

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

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

Recap: Functions as first-class values

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

CSE 130 [Winter 2014] Programming Languages

PROGRAMMING IN HASKELL. CS Chapter 6 - Recursive Functions

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

CSE 130: Programming Languages. Polymorphism. Ranjit Jhala UC San Diego

Recap: ML s Holy Trinity

Programming Languages

F28PL1 Programming Languages. Lecture 14: Standard ML 4

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

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

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

List Functions, and Higher-Order Functions

Programming Languages

CSc 520 Principles of Programming Languages. Currying Revisited... Currying Revisited. 16: Haskell Higher-Order Functions

CSc 372. Comparative Programming Languages. 11 : Haskell Higher-Order Functions. Department of Computer Science University of Arizona

Programming Languages

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

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

CMSC 330, Fall 2013, Practice Problems 3

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

CMSC 330, Fall 2013, Practice Problem 3 Solutions

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

CSCE 314 TAMU Fall CSCE 314: Programming Languages Dr. Flemming Andersen. Haskell Functions

CSE341: Programming Languages Lecture 2 Functions, Pairs, Lists. Zach Tatlock Winter 2018

Function definitions. CSE341: Programming Languages Lecture 2 Functions, Pairs, Lists. Example, extended. Some gotchas. Zach Tatlock Winter 2018

CSE 341 Section 5. Winter 2018

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

So what does studying PL buy me?

CSci 4223 Principles of Programming Languages

CSE341 Spring 2017, Midterm Examination April 28, 2017

Programming Language Concepts: Lecture 14

Topic 5: Examples and higher-order functions

CS 457/557: Functional Languages

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

CSCI 2041: First Class Functions

Introduction to OCaml

INF121: Functional Algorithmic and Programming

An introduction introduction to functional functional programming programming using usin Haskell

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

Shell CSCE 314 TAMU. Functions continued

Lecture 10 September 11, 2017

Lecture 19: Functions, Types and Data Structures in Haskell

Programming Languages

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

02157 Functional Programming Tagged values and Higher-order list functions

Watch out for the arrows. Recollecting Haskell, Part V. A start on higher types: Mapping, 1. A start on higher types: Mapping, 2.

Shell CSCE 314 TAMU. Haskell Functions

CSCE 314 Programming Languages

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

CSc 372 Comparative Programming Languages

Shell CSCE 314 TAMU. Higher Order Functions

The List Datatype. CSc 372. Comparative Programming Languages. 6 : Haskell Lists. Department of Computer Science University of Arizona

Programming Languages Lecture 14: Sum, Product, Recursive Types

CS 321 Programming Languages

PROGRAMMING IN HASKELL. Chapter 5 - List Comprehensions

CSc 372. Comparative Programming Languages. 8 : Haskell Function Examples. Department of Computer Science University of Arizona

Introduction to Programming: Lecture 6

INTRODUCTION TO HASKELL

Informatics 1 Functional Programming Lecture 4. Lists and Recursion. Don Sannella University of Edinburgh

Carlos Varela RPI September 19, Adapted with permission from: Seif Haridi KTH Peter Van Roy UCL

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

Lecture 6: Sequential Sorting

CSE 130, Fall 2005: Final Examination

CSE341, Fall 2011, Midterm Examination October 31, 2011

CSE341 Spring 2016, Midterm Examination April 29, 2016

Parametric types. map: ( a (a b) a list b list. filter: ( a bool) a list a list. Why? a and b are type variables!

CSE 130, Fall 2006: Final Examination

CSE 341 : Programming Languages Midterm, Spring 2015

COSE212: Programming Languages. Lecture 3 Functional Programming in OCaml

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

Transcription:

CSE 130: Winter 2010 News Programming Languages Lecture 8: Higher-Order Od Functions Ranjit Jhala UC San Diego Today s Plan Finish Static Scoping Tail Recursion last thing function does is a recursive call Practice with recursion [TAIL REC] Base Pattern -> Base Expression Induction Pattern -> Induction Expression let rec rev = function x::xs -> (rev xs) @ [x] NOT TR Higher-Order Functions or, why take and return functions? bad because height of stack = O(n)

Tail Recursive Rev last thing function does is a recursive call let rec rev xs = Today s Plan Finish Static Scoping Practice with recursion Base Pattern -> Base Expression Induction Pattern -> Induction Expression Higher-Order Functions or, why take and return functions? Functions are first-class values Arguments, return values, bindings What are the benefits? Returning functions let lt = fun x -> fun y -> x < y; Returned value is a function let lt x y = x < y;; Creating, (Returning) Functions Identical but easier to write! In general, these two are equivalent: let f = fun x1 -> -> fun xn -> e let f x1 xn = e

Returning functions let lt x y = x < y; let lt = fun x -> fun y -> x < y lt 5 20;; lt 20 7;; let is5lt = lt 5;; int (int bool) let is10lt = lt 10;; Parameterized tester Create many similar testers Where is this useful? Remember this? Tail Rec? let rec sort lt l = (h::t) = let (l,r) = partition (lt h) t in (sort lt l)@(h::(sort lt r)) ;; Use tester to partition list Tester parameterized by pivot h Reuse code to sort any type of list Use different lt to sort in different orders Function Currying Function Currying Tuple version: let f (x1,,xn) = e T 1 * * T n T Multiple argument functions by returning a function that takes the next argument Named after a person (Haskell Curry) let lt x y = x < y; Curried version: let f x1 xn = e T 1 T n T Could have done: let lt (x,y) = x<y; But then no testers possible Must pick good order of arguments

Using parameterized testers let rec sort lt l = (h::t) = let (l,r) = partition (lt h) t in (sort lt l)@(h::(sort lt r)) ;; partition Takes a tester (and a list) as argument Returns a pair: (list passing test, list failing test) Can be called with any tester! Functions are first-class values Arguments, return values, bindings What are the benefits? Parameterized, similar functions (e.g. Testers) Creating, (Returning) Functions Using, (Taking) Functions Useful if parameterized functions can be passed to, hence used/called by other functions Why take functions as input? let rec evens = function h::t -> if is_even h then h::(evens t) else evens t Factoring and Reuse let rec evens = function h::t -> if is_even h then h::(evens t) else evens t let rec lessers x = function h::t -> if x>h then h::(lessers x t) else lessers x t let rec filter f = function h::t -> if f h then h::(filter f t)else filter f t let rec filter f = function h::t -> if f h then h::(filter f t)else filter f t Factor code: Generic pattern x Specific instance let evens x ys = filter is_even ys

Factoring and Reuse let rec lessers x = function h::t -> if x>h then h::(lessers x t) else lessers x t let rec filter f = function h::t -> if f h then h::(filter f t)else filter f t Factor code: Generic pattern x Specific instance let lessers x ys = filter ((>) x) ys Encoding Patterns as functions let rec filter f = function []-> [] h::t-> if f h then h::(filter f t) else filter f t let neg f = fun x -> not (f x) let partition f l= (filter f l, filter(neg f) l)) filter,neg,partition higher-order functions take a any tester as argument! Iteration Pattern let rec listuppercase xs = match xs with h::t -> (uppercase h)::(listuppercase t) let rec listsquare xs = match xs with h::t -> (h * h)::(listsquare t) let addpair (x,y) = x + y let rec listaddpair xs = (hx,hy)::t ->(addpair (hx,hy))::(listaddpair t) Iteration Pattern let rec listuppercase xs = let match rec xsmap with f l = h::t -> (uppercase h)::(listuppercase uppercase t) (h::t) -> (f h)::(map f t) let listuppercase xs = map uppercase xs let listsquare xs = map (fun x -> x*x) xs let listaddpair i xs = map(fun(x,y)->x+y) ( ) xs

Higher-order functions: map let rec map f l = (h::t) -> (f h)::(map f t) Type says it all! ( a (a b) a list b list Applies f to each element in input list Makes a list of the results Factoring Iteration w/ map let rec map f l = (h::t) -> (f h)::(map f t) Factored code: Reuse iteration template Avoid bugs due to repetition Fix bug in one place! Another pattern: Accumulation let max x y = if x > y then x else y ; let listmax l = let rec help cur l = [] -> cur h::t -> help (max cur h) t in helper 0 l;; let concat l = let rec help cur l = [] -> cur h::t -> help (cur^h) t in helper l;; Whats the pattern?

Whats the pattern? Whats the pattern? Tail Rec? Whats the pattern? Tail Rec? Let rec fold f cur l = case l of [] -> cur h::t -> fold f (f cur h) t What is: fold f base [v1;v2; ;vn]? f( ( ( f(,v3),vn) f(base,v1) f(,v2) f(,v3) f( (,vn) Examples of fold Currying! This is a function! let listmax = fold max 0 Currying! This is a function! let concat = fold (^) let multiplier = Pick correct base case! Currying! This is a function! fold (*) 1

Examples of fold Funcs taking/returning funcs Identify common computation patterns Filter values in a set, list, tree Iterate a function over a set, list, tree map What does this do? let f l = fold (::) [] l Accumulate some value over a collection fold Pull out (factor) common code: Computation ti Patterns Re-usein many different situations Another fun function: pipe let pipe x f = f x let ( >) x f = f x Compute the sum of squares of numbers in a list? let sumofsquares xs = xs > map (fun x -> x * x) > fold_left (+) 0 Tail Rec? Funcs taking/returning funcs Identify common computation patterns Filter values in a set, list, tree map Convert a function over a set, list, tree Iterate a function over a set, list, tree Accumulate some value over a collection fold Pull out (factor) common code: Computation o Patterns Re-usein many different situations