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

Similar documents
CSE341: Programming Languages Winter 2018 Unit 3 Summary Zach Tatlock, University of Washington

CSci 4223 Principles of Programming Languages

CSE 341 Section 5. Winter 2018

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

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

CSE341: Programming Languages Lecture 11 Type Inference. Dan Grossman Spring 2016

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

CSci 4223 Principles of Programming Languages

CSE341, Fall 2011, Midterm Examination October 31, 2011

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

CSE341: Programming Languages Lecture 4 Records, Datatypes, Case Expressions. Dan Grossman Spring 2013

CSE341, Fall 2011, Midterm Examination October 31, 2011

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

Exercises on ML. Programming Languages. Chanseok Oh

CSE413: Programming Languages and Implementation Racket structs Implementing languages with interpreters Implementing closures

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

CSE 413 Languages & Implementation. Hal Perkins Winter 2019 Structs, Implementing Languages (credits: Dan Grossman, CSE 341)

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

CSci 4223 Lecture 12 March 4, 2013 Topics: Lexical scope, dynamic scope, closures

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

CSE 341: Programming Languages

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

CSE 341 : Programming Languages

CSE341 Spring 2016, Midterm Examination April 29, 2016

CSE341: Programming Languages Lecture 2 Functions, Pairs, Lists. Dan Grossman Fall 2011

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

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

CSCI-GA Scripting Languages

Datatype declarations

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

CSE341 Autumn 2017, Midterm Examination October 30, 2017

CSE341 Spring 2016, Midterm Examination April 29, 2016

CS 320: Concepts of Programming Languages

List Functions, and Higher-Order Functions

CSE 341: Programming Languages

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

Fall Lecture 3 September 4. Stephen Brookes

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

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

CSE341, Spring 2013, Final Examination June 13, 2013

CMSC 330, Fall 2013, Practice Problems 3

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

Recap: Functions as first-class values

Lecture 3: Recursion; Structural Induction

Introduction to OCaml

CSE341: Programming Languages Lecture 19 Introduction to Ruby and OOP. Dan Grossman Winter 2013

Standard ML. Data types. ML Datatypes.1

CSE341: Programming Languages Lecture 17 Implementing Languages Including Closures. Dan Grossman Autumn 2018

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

FUNCTIONAL PROGRAMMING

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

CS 320: Concepts of Programming Languages

CMSC 330, Fall 2013, Practice Problem 3 Solutions

Programming Languages

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

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

INF 212 ANALYSIS OF PROG. LANGS FUNCTION COMPOSITION. Instructors: Crista Lopes Copyright Instructors.

Mini-ML. CS 502 Lecture 2 8/28/08

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

Lists. Michael P. Fourman. February 2, 2010

Ruby logistics. CSE341: Programming Languages Lecture 19 Introduction to Ruby and OOP. Ruby: Not our focus. Ruby: Our focus. A note on the homework

INF 102 CONCEPTS OF PROG. LANGS FUNCTIONAL COMPOSITION. Instructors: James Jones Copyright Instructors.

Begin at the beginning

Lecture 19: Functions, Types and Data Structures in Haskell

CSE341: Programming Languages Lecture 26 Course Victory Lap. Dan Grossman Spring 2016

CMSC330. Objects, Functional Programming, and lambda calculus

ML Built-in Functions

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

CSE 3302 Programming Languages Lecture 8: Functional Programming

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

CSE 341, Autumn 2005, Assignment 3 ML - MiniML Interpreter

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

An introduction to functional programming. July 23, 2010

Lecture 2: Big-Step Semantics

CSE341 Spring 2016, Final Examination June 6, 2016

Variables and Bindings

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

A Brief Introduction to Standard ML

Higher-Order Functions

CSc 372 Comparative 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

Haskell: Lists. CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Friday, February 24, Glenn G.

The type checker will complain that the two branches have different types, one is string and the other is int

SNU Programming Language Theory

Programming Languages and Compilers (CS 421)

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

Lambda Calculus and Type Inference

15 150: Principles of Functional Programming. More about Higher-Order Functions

SML A F unctional Functional Language Language Lecture 19

Introduction to OCaml

Haskell Introduction Lists Other Structures Data Structures. Haskell Introduction. Mark Snyder

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

Whereweare. CS-XXX: Graduate Programming Languages. Lecture 7 Lambda Calculus. Adding data structures. Data + Code. What about functions

Inductive Data Types

A Concepts-Focused Introduction to Functional Programming Using Standard ML Sample Exam #1 Draft of August 12, 2010

Functional Paradigm II

A First Look at ML. Chapter Five Modern Programming Languages, 2nd ed. 1

CSE 341: Programming Languages

(Refer Slide Time: 4:00)

Transcription:

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

What is functional programming? Functional programming can mean a few different things: 1. Avoiding mutation in most/all cases (done and ongoing) 2. Using functions as values (this unit) Style encouraging recursion and recursive data structures Style closer to mathematical definitions Programming idioms using laziness (later topic, briefly) Anything not OOP or C? (not a good definition) Not sure a definition of functional language exists beyond makes functional programming easy / the default / required No clear yes/no for a particular language 2

First-class functions First-class functions: Can use them wherever we use values Functions are values too Arguments, results, parts of tuples, bound to variables, carried by datatype constructors or exceptions, fun double x = 2*x fun incr x = x+1 val a_tuple = (double, incr, double(incr 7)) Most common use is as an argument / result of another function Other function is called a higher-order function Powerful way to factor out common functionality 3

Function Closures Function closure: Functions can use bindings from outside the function definition (in scope where function is defined) Makes first-class functions much more powerful Will get to this feature in a bit, after simpler examples Distinction between terms first-class functions and function closures is not universally understood Important conceptual distinction even if terms get muddled 4

Onward The next week: How to use first-class functions and closures The precise semantics Multiple powerful idioms 5

Functions as arguments We can pass one function as an argument to another function Not a new feature, just never thought to do it before fun f (g, ) = g ( ) fun h1 = fun h2 = f(h1, ) f(h2, ) Elegant strategy for factoring out common code Replace N similar functions with calls to 1 function where you pass in N different (short) functions as arguments [See the code file for this lecture] 6

Example Can reuse n_times rather than defining many similar functions Computes f(f( f(x))) where number of calls is n fun n_times (f,n,x) = if n=0 then x else f (n_times(f,n-1,x)) fun double x = x + x fun increment x = x + 1 val x1 = n_times(double,4,7) val x2 = n_times(increment,4,7) val x3 = n_times(tl,2,[4,8,12,16]) fun double_n_times (n,x) = n_times(double,n,x) fun nth_tail (n,x) = n_times(tl,n,x) 7

Relation to types Higher-order functions are often so generic and reusable that they have polymorphic types, i.e., types with type variables But there are higher-order functions that are not polymorphic And there are non-higher-order (first-order) functions that are polymorphic Always a good idea to understand the type of a function, especially a higher-order function 8

Types for example fun n_times (f,n,x) = if n=0 then x else f (n_times(f,n-1,x)) val n_times : ('a -> 'a) * int * 'a -> 'a Simpler but less useful: (int -> int) * int * int -> int Two of our examples instantiated 'a with int One of our examples instantiated 'a with int list This polymorphism makes n_times more useful Type is inferred based on how arguments are used (later lecture) Describes which types must be exactly something (e.g., int) and which can be anything but the same (e.g., 'a) 9

Polymorphism and higher-order functions Many higher-order functions are polymorphic because they are so reusable that some types, can be anything But some polymorphic functions are not higher-order Example: len : 'a list -> int And some higher-order functions are not polymorphic Example: times_until_0 : (int -> int) * int -> int fun times_until_0 (f,x) = if x=0 then 0 else 1 + times_until_0(f, f x) Note: Would be better with tail-recursion 10

Toward anonymous functions Definitions unnecessarily at top-level are still poor style: fun triple x = 3*x fun triple_n_times (f,x) = n_times(triple,n,x) So this is better (but not the best): fun triple_n_times (f,x) = let fun trip y = 3*y in n_times(trip,n,x) end And this is even smaller scope It makes sense but looks weird (poor style; see next slide) fun triple_n_times (f,x) = n_times(let fun trip y = 3*y in trip end, n, x) 11

Anonymous functions This does not work: A function binding is not an expression fun triple_n_times (f,x) = n_times((fun trip y = 3*y), n, x) This is the best way we were building up to: an expression form for anonymous functions fun triple_n_times (f,x) = n_times((fn y => 3*y), n, x) Like all expression forms, can appear anywhere Syntax: fn not fun => not = no function name, just an argument pattern 12

Using anonymous functions Most common use: Argument to a higher-order function Don t need a name just to pass a function But: Cannot use an anonymous function for a recursive function Because there is no name for making recursive calls If not for recursion, fun bindings would be syntactic sugar for val bindings and anonymous functions fun triple x = 3*x val triple = fn y => 3*y 13

A style point Compare: if x then true else false With: (fn x => f x) So don t do this: n_times((fn y => tl y),3,xs) When you can do this: n_times(tl,3,xs) 14

Map fun map (f,xs) = case xs of [] => [] x::xs => (f x)::(map(f,xs )) val map : ('a -> 'b) * 'a list -> 'b list Map is, without doubt, in the higher-order function hall-of-fame The name is standard (for any data structure) You use it all the time once you know it: saves a little space, but more importantly, communicates what you are doing Similar predefined function: List.map But it uses currying (coming soon) 15

Filter fun filter (f,xs) = case xs of [] => [] x::xs => if f x then x::(filter(f,xs )) else filter(f,xs ) val filter : ('a -> bool) * 'a list -> 'a list Filter is also in the hall-of-fame So use it whenever your computation is a filter Similar predefined function: List.filter But it uses currying (coming soon) 16

Generalizing Our examples of first-class functions so far have all: Taken one function as an argument to another function Processed a number or a list But first-class functions are useful anywhere for any kind of data Can pass several functions as arguments Can put functions in data structures (tuples, lists, etc.) Can return functions as results Can write higher-order functions that traverse your own data structures Useful whenever you want to abstract over what to compute with No new language features 17

Returning functions Remember: Functions are first-class values For example, can return them from functions Silly example: fun double_or_triple f = if f 7 then fn x => 2*x else fn x => 3*x Has type (int -> bool) -> (int -> int) But the REPL prints (int -> bool) -> int -> int because it never prints unnecessary parentheses and t1 -> t2 -> t3 -> t4 means t1->(t2->(t3->t4)) 18

Other data structures Higher-order functions are not just for numbers and lists They work great for common recursive traversals over your own data structures (datatype bindings) too Example of a higher-order predicate: Are all constants in an arithmetic expression even numbers? Use a more general function of type (int -> bool) * exp -> bool And call it with (fn x => x mod 2 = 0) 19