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

Slides:



Advertisements
Similar presentations
Types and Programming Languages Lecture 7 Simon Gay Department of Computing Science University of Glasgow 2006/07.
Advertisements

Higher-order functions in ML
Modern Programming Languages, 2nd ed.
ML Lists.1 Standard ML Lists. ML Lists.2 Lists  A list is a finite sequence of elements. [3,5,9] ["a", "list" ] []  Elements may appear more than once.
A First Look at ML.
A Third Look At ML 1. Outline More pattern matching Function values and anonymous functions Higher-order functions and currying Predefined higher-order.
Type Checking, Inference, & Elaboration CS153: Compilers Greg Morrisett.
CSE341: Programming Languages Lecture 2 Functions, Pairs, Lists Dan Grossman Winter 2013.
CMSC 330: Organization of Programming Languages Tuples, Types, Conditionals and Recursion or “How many different OCaml topics can we cover in a single.
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.
ML Datatypes.1 Standard ML Data types. ML Datatypes.2 Concrete Datatypes  The datatype declaration creates new types  These are concrete data types,
Getting started with ML ML is a functional programming language. ML is statically typed: The types of literals, values, expressions and functions in a.
Lambda Calculus and Lisp PZ03J. Lambda Calculus The lambda calculus is a model for functional programming like Turing machines are models for imperative.
ML: a quasi-functional language with strong typing Conventional syntax: - val x = 5; (*user input *) val x = 5: int (*system response*) - fun len lis =
Chapter ElevenModern Programming Languages1 A Fourth Look At ML.
A Fourth Look At ML Chapter ElevenModern Programming Languages, 2nd ed.1.
A First Look at ML Chapter FiveModern Programming Languages, 2nd ed.1.
Patterns in ML 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 the.
5/11/2015IT 3271 Types in ML (Ch 11) datatype bool = true | false; datatype 'element list = nil | :: of 'element * 'element list n Predefined, but not.
CSE341: Programming Languages Lecture 5 Pattern-Matching Dan Grossman Fall 2011.
CSE341: Programming Languages Lecture 7 Functions Taking/Returning Functions Dan Grossman Fall 2011.
0 PROGRAMMING IN HASKELL Chapter 7 - Higher-Order Functions.
Chapter 9 More About Higher-Order Functions. Currying Recall the function: simple n a b = n * (a+b) Note that: simple n a b is really (((simple n) a)
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.
Advanced Programming Handout 7 More About Higher-Order Functions (SOE Chapter 9)
1 Functional languages (e.g. Scheme, ML) Scheme is a functional language. Scheme is based on lambda calculus. lambda abstraction = function definition.
Chapter 5 Polymorphic and Higher-Order Functions.
Cse536 Functional Programming 1 7/14/2015 Lecture #2, Sept 29, 2004 Reading Assignments –Begin Chapter 2 of the Text Home work #1 can be found on the webpage,
Functional Programming Element of Functional Programming.
Chapter TwelveModern Programming Languages1 Memory Locations For Variables.
© Kenneth C. Louden, Chapter 11 - Functional Programming, Part III: Theory Programming Languages: Principles and Practice, 2nd Ed. Kenneth C. Louden.
CSE-321 Programming Languages Introduction to Functional Programming (Part II) POSTECH March 13, 2006 박성우.
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.
Chapter Twenty-ThreeModern Programming Languages1 Formal Semantics.
Formal Semantics Chapter Twenty-ThreeModern Programming Languages, 2nd ed.1.
Chapter 9: Functional Programming in a Typed Language.
1-Nov-15 Haskell II Functions and patterns. Data Types Int + - * / ^ even odd Float + - * / ^ sin cos pi truncate Char ord chr isSpace isUpper … Bool.
A Second Look At ML 1. Outline Patterns Local variable definitions A sorting example 2.
© Kenneth C. Louden, Chapter 11 - Functional Programming, Part III: Theory Programming Languages: Principles and Practice, 2nd Ed. Kenneth C. Louden.
0 Odds and Ends in Haskell: Folding, I/O, and Functors Adapted from material by Miran Lipovaca.
Lee CSCE 314 TAMU 1 CSCE 314 Programming Languages Haskell: Higher-order Functions Dr. Hyunyoung Lee.
Error Example - 65/4; ! Toplevel input: ! 65/4; ! ^^ ! Type clash: expression of type ! int ! cannot have type ! real.
Chapter SevenModern Programming Languages1 A Second Look At ML.
A FIRST LOOK AT ML Chapter Five Modern Programming Languages 1.
CSE 341 : Programming Languages Lecture 8 First Class Functions Zach Tatlock Spring 2014.
Recursion Higher Order Functions CSCE 314 Spring 2016.
Haskell Chapter 5, Part II. Topics  Review/More Higher Order Functions  Lambda functions  Folds.
CSE 341 Lecture 8 curried functions Ullman 5.5 slides created by Marty Stepp
Cs776(Prasad)L6sml971 SML-97 Specifics SML/NJ 110.
1.SML Docs Standard Basis 2.First-Class Functions Anonymous Style Points Higher-Order 3.Examples Agenda.
1 Objective Caml (Ocaml) Aaron Bloomfield CS 415 Fall 2005.
6-Jul-16 Haskell II Functions and patterns. Data Types Int + - * / ^ even odd Float + - * / ^ sin cos pi truncate Char ord chr isSpace isUpper … Bool.
Set Comprehensions In mathematics, the comprehension notation can be used to construct new sets from old sets. {x2 | x  {1...5}} The set {1,4,9,16,25}
Set Comprehensions In mathematics, the comprehension notation can be used to construct new sets from old sets. {x2 | x  {1...5}} The set {1,4,9,16,25}
ML: a quasi-functional language with strong typing
Functions and patterns
ML Again ( Chapter 7) Patterns Local variable definitions
A lightening tour in 45 minutes
PROGRAMMING IN HASKELL
Agenda SML Docs First-Class Functions Examples Standard Basis
Agenda SML Docs First-Class Functions Examples Standard Basis
CSE 341 Section 5 Winter 2018.
CSE-321 Programming Languages Introduction to Functional Programming
CSE 3302 Programming Languages
Functions and patterns
CSE 341 Lecture 11 b closures; scoping rules
Programming Languages Dan Grossman 2013
CSE341: Programming Languages Lecture 12 Equivalence
Presentation transcript:

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

Outline n More pattern matching n Function values and anonymous functions n Higher-order functions and currying n Predefined higher-order functions Chapter NineModern Programming Languages, 2nd ed.2

More Pattern-Matching n Last time we saw pattern-matching in function definitions: – fun f 0 = "zero" | f _ = "non-zero"; n Pattern-matching occurs in several other kinds of ML expressions: – case n of 0 => "zero" | _ => "non-zero"; Chapter NineModern Programming Languages, 2nd ed.3

Match Syntax n A rule is a piece of ML syntax that looks like this: n A match consists of one or more rules separated by a vertical bar, like this: n Each rule in a match must have the same type of expression on the right-hand side n A match is not an expression by itself, but forms a part of several kinds of ML expressions Chapter NineModern Programming Languages, 2nd ed.4 ::= => ::= | '|'

Case Expressions n The syntax is n This is a very powerful case construct—unlike many languages, it does more than just compare with constants Chapter NineModern Programming Languages, 2nd ed.5 - case 1+1 of = 3 => "three" | = 2 => "two" | = _ => "hmm"; val it = "two" : string ::= case of

Example Chapter NineModern Programming Languages, 2nd ed.6 case x of _::_::c::_ => c | _::b::_ => b | a::_ => a | nil => 0 The value of this expression is the third element of the list x, if it has at least three, or the second element if x has only two, or the first element if x has only one, or 0 if x is empty.

Generalizes if n The two expressions above are equivalent So if - then - else is really just a special case of case Chapter NineModern Programming Languages, 2nd ed.7 if exp 1 then exp 2 else exp 3 case exp 1 of true => exp 2 | false => exp 3

Outline n More pattern matching n Function values and anonymous functions n Higher-order functions and currying n Predefined higher-order functions Chapter NineModern Programming Languages, 2nd ed.8

Predefined Functions n When an ML language system starts, there are many predefined variables n Some are bound to functions: Chapter NineModern Programming Languages, 2nd ed.9 - ord; val it = fn : char -> int - ~; val it = fn : int -> int

Defining Functions We have seen the fun notation for defining new named functions You can also define new names for old functions, using val just as for other kinds of values: Chapter NineModern Programming Languages, 2nd ed.10 - val x = ~; val x = fn : int -> int - x 3; val it = ~3 : int

Function Values n Functions in ML do not have names n Just like other kinds of values, function values may be given one or more names by binding them to variables The fun syntax does two separate things: – Creates a new function value – Binds that function value to a name Chapter NineModern Programming Languages, 2nd ed.11

Anonymous Functions n Named function: n Anonymous function: Chapter NineModern Programming Languages, 2nd ed.12 - fun f x = x + 2; val f = fn : int -> int - f 1; val it = 3 : int - fn x => x + 2; val it = fn : int -> int - (fn x => x + 2) 1; val it = 3 : int

The fn Syntax n Another use of the match syntax Using fn, we get an expression whose value is an (anonymous) function We can define what fun does in terms of val and fn n These two definitions have the same effect: – fun f x = x + 2 – val f = fn x => x + 2 Chapter NineModern Programming Languages, 2nd ed.13 ::= fn

Using Anonymous Functions n One simple application: when you need a small function in just one place Without fn : With fn : Chapter NineModern Programming Languages, 2nd ed.14 - fun intBefore (a,b) = a bool - quicksort ([1,4,3,2,5], intBefore); val it = [1,2,3,4,5] : int list - quicksort ([1,4,3,2,5], fn (a,b) => a a>b); val it = [5,4,3,2,1] : int list

The op keyword n Binary operators are special functions Sometimes you want to treat them like plain functions: to pass bool The keyword op before an operator gives you the underlying function Chapter NineModern Programming Languages, 2nd ed.15 - op *; val it = fn : int * int -> int - quicksort ([1,4,3,2,5], op <); val it = [1,2,3,4,5] : int list

Outline n More pattern matching n Function values and anonymous functions n Higher-order functions and currying n Predefined higher-order functions Chapter NineModern Programming Languages, 2nd ed.16

Higher-order Functions n Every function has an order: – A function that does not take any functions as parameters, and does not return a function value, has order 1 – A function that takes a function as a parameter or returns a function value has order n+1, where n is the order of its highest-order parameter or returned value The quicksort we just saw is a second-order function Chapter NineModern Programming Languages, 2nd ed.17

Practice Chapter NineModern Programming Languages, 2nd ed.18 What is the order of functions with each of the following ML types? int * int -> bool int list * (int * int -> bool) -> int list int -> int -> int (int -> int) * (int -> int) -> (int -> int) int -> bool -> real -> string What can you say about the order of a function with this type? ('a -> 'b) * ('c -> 'a) -> 'c -> 'b

Currying We've seen how to get two parameters into a function by passing a 2-tuple: fun f (a,b) = a + b; Another way is to write a function that takes the first argument, and returns another function that takes the second argument: fun g a = fn b => a+b; n The general name for this is currying Chapter NineModern Programming Languages, 2nd ed.19

Curried Addition n Remember that function application is left- associative So g 2 3 means ((g 2) 3) Chapter NineModern Programming Languages, 2nd ed.20 - fun f (a,b) = a+b; val f = fn : int * int -> int - fun g a = fn b => a+b; val g = fn : int -> int -> int - f(2,3); val it = 5 : int - g 2 3; val it = 5 : int

Advantages No tuples: we get to write g 2 3 instead of f(2,3) n But the real advantage: we get to specialize functions for particular initial parameters Chapter NineModern Programming Languages, 2nd ed.21 - val add2 = g 2; val add2 = fn : int -> int - add2 3; val it = 5 : int - add2 10; val it = 12 : int

Advantages: Example Like the previous quicksort n But now, the comparison function is a first, curried parameter Chapter NineModern Programming Languages, 2nd ed.22 - quicksort (op <) [1,4,3,2,5]; val it = [1,2,3,4,5] : int list - val sortBackward = quicksort (op >); val sortBackward = fn : int list -> int list - sortBackward [1,4,3,2,5]; val it = [5,4,3,2,1] : int list

Multiple Curried Parameters n Currying generalizes to any number of parameters Chapter NineModern Programming Languages, 2nd ed.23 - fun f (a,b,c) = a+b+c; val f = fn : int * int * int -> int - fun g a = fn b => fn c => a+b+c; val g = fn : int -> int -> int -> int - f (1,2,3); val it = 6 : int - g 1 2 3; val it = 6 : int

Notation For Currying n There is a much simpler notation for currying (on the next slide) n The long notation we have used so far makes the little intermediate anonymous functions explicit n But as long as you understand how it works, the simpler notation is much easier to read and write Chapter NineModern Programming Languages, 2nd ed.24 fun g a = fn b => fn c => a+b+c;

Easier Notation for Currying Instead of writing: fun f a = fn b => a+b; We can just write: fun f a b = a+b; n This generalizes for any number of curried arguments Chapter NineModern Programming Languages, 2nd ed.25 - fun f a b c d = a+b+c+d; val f = fn : int -> int -> int -> int -> int

Outline n More pattern matching n Function values and anonymous functions n Higher-order functions and currying n Predefined higher-order functions Chapter NineModern Programming Languages, 2nd ed.26

Predefined Higher-Order Functions n We will use three important predefined higher-order functions: – map – foldr – foldl Actually, foldr and foldl are very similar, as you might guess from the names Chapter NineModern Programming Languages, 2nd ed.27

The map Function n Used to apply a function to every element of a list, and collect a list of results Chapter NineModern Programming Languages, 2nd ed.28 - map ~ [1,2,3,4]; val it = [~1,~2,~3,~4] : int list - map (fn x => x+1) [1,2,3,4]; val it = [2,3,4,5] : int list - map (fn x => x mod 2 = 0) [1,2,3,4]; val it = [false,true,false,true] : bool list - map (op +) [(1,2),(3,4),(5,6)]; val it = [3,7,11] : int list

The map Function Is Curried Chapter NineModern Programming Languages, 2nd ed.29 - map; val it = fn : ('a -> 'b) -> 'a list -> 'b list - val f = map (op +); val f = fn : (int * int) list -> int list - f [(1,2),(3,4)]; val it = [3,7] : int list

The foldr Function n Used to combine all the elements of a list For example, to add up all the elements of a list x, we could write foldr (op +) 0 x n It takes a function f, a starting value c, and a list x = [x 1, …, x n ] and computes: So foldr (op +) 0 [1,2,3,4] evaluates as 1+(2+(3+(4+0)))=10 Chapter NineModern Programming Languages, 2nd ed.30

Examples Chapter NineModern Programming Languages, 2nd ed.31 - foldr (op +) 0 [1,2,3,4]; val it = 10 : int - foldr (op * ) 1 [1,2,3,4]; val it = 24 : int - foldr (op ^) "" ["abc","def","ghi"]; val it = "abcdefghi" : string - foldr (op ::) [5] [1,2,3,4]; val it = [1,2,3,4,5] : int list

The foldr Function Is Curried Chapter NineModern Programming Languages, 2nd ed.32 - foldr; val it = fn : ('a * 'b -> 'b) -> 'b -> 'a list -> 'b - foldr (op +); val it = fn : int -> int list -> int - foldr (op +) 0; val it = fn : int list -> int - val addup = foldr (op +) 0; val addup = fn : int list -> int - addup [1,2,3,4,5]; val it = 15 : int

The foldl Function n Used to combine all the elements of a list Same results as foldr in some cases Chapter NineModern Programming Languages, 2nd ed.33 - foldl (op +) 0 [1,2,3,4]; val it = 10 : int - foldl (op * ) 1 [1,2,3,4]; val it = 24 : int

The foldl Function To add up all the elements of a list x, we could write foldl (op +) 0 x n It takes a function f, a starting value c, and a list x = [x 1, …, x n ] and computes: So foldl (op +) 0 [1,2,3,4] evaluates as 4+(3+(2+(1+0)))=10 Remember, foldr did 1+(2+(3+(4+0)))=10 Chapter NineModern Programming Languages, 2nd ed.34

The foldl Function foldl starts at the l eft, foldr starts at the r ight Difference does not matter when the function is associative and commutative, like + and * n For other operations, it does matter Chapter NineModern Programming Languages, 2nd ed.35 - foldr (op ^) "" ["abc","def","ghi"]; val it = "abcdefghi" : string - foldl (op ^) "" ["abc","def","ghi"]; val it = "ghidefabc" : string - foldr (op -) 0 [1,2,3,4]; val it = ~2 : int - foldl (op -) 0 [1,2,3,4]; val it = 2 : int