A Third Look At ML 1. Outline More pattern matching Function values and anonymous functions Higher-order functions and currying Predefined higher-order.

Slides:



Advertisements
Similar presentations
1 Vorlesung Informatik 2 Algorithmen und Datenstrukturen (Parallel Algorithms) Robin Pomplun.
Advertisements

Copyright © 2002 Pearson Education, Inc. Slide 1.
Copyright © 2003 Pearson Education, Inc. Slide 1.
Chapter 7 Constructors and Other Tools. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-2 Learning Objectives Constructors Definitions.
Copyright © 2003 Pearson Education, Inc. Slide 1 Computer Systems Organization & Architecture Chapters 8-12 John D. Carpinelli.
Copyright © 2011, Elsevier Inc. All rights reserved. Chapter 6 Author: Julia Richards and R. Scott Hawley.
Author: Julia Richards and R. Scott Hawley
Properties Use, share, or modify this drill on mathematic properties. There is too much material for a single class, so you’ll have to select for your.
UNITED NATIONS Shipment Details Report – January 2006.
1 RA I Sub-Regional Training Seminar on CLIMAT&CLIMAT TEMP Reporting Casablanca, Morocco, 20 – 22 December 2005 Status of observing programmes in RA I.
Properties of Real Numbers CommutativeAssociativeDistributive Identity + × Inverse + ×
FACTORING ax2 + bx + c Think “unfoil” Work down, Show all steps.
Programming Language Concepts
Haskell user defined types data Temp = Cold|Hot|Warm deriving (Show,Eq, Ord, Enum) -- to enable printing to screen -- comparing for equality -- comparison.
Solve Multi-step Equations
Introduction A function is called higher-order if it takes a function as an argument or returns a function as a result. twice :: (a  a)  a  a twice.
REVIEW: Arthropod ID. 1. Name the subphylum. 2. Name the subphylum. 3. Name the order.
Week 2 The Object-Oriented Approach to Requirements
EE, NCKU Tien-Hao Chang (Darby Chang)
Turing Machines.
Chair of Software Engineering Einführung in die Programmierung Introduction to Programming Prof. Dr. Bertrand Meyer Exercise Session 5.
PP Test Review Sections 6-1 to 6-6
0 PROGRAMMING IN HASKELL Chapter 5 - List Comprehensions.
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 [3,4]
EU market situation for eggs and poultry Management Committee 20 October 2011.
EIS Bridge Tool and Staging Tables September 1, 2009 Instructor: Way Poteat Slide: 1.
1 University of Utah – School of Computing Computer Science 1021 "Thinking Like a Computer"
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.
How to convert a left linear grammar to a right linear grammar
Basel-ICU-Journal Challenge18/20/ Basel-ICU-Journal Challenge8/20/2014.
1..
A First Look at ML.
A Fourth Look At ML 1. Type Definitions Predefined, but not primitive in ML: Type constructor for lists: Defined for ML in ML datatype bool = true | false;
CONTROL VISION Set-up. Step 1 Step 2 Step 3 Step 5 Step 4.
© 2012 National Heart Foundation of Australia. Slide 2.
Adding Up In Chunks.
Copyright © 2013 by John Wiley & Sons. All rights reserved. HOW TO CREATE LINKED LISTS FROM SCRATCH CHAPTER Slides by Rick Giles 16 Only Linked List Part.
1 of 32 Images from Africa. 2 of 32 My little Haitian friend Antoine (1985)
Formal Language, chapter 10, slide 1Copyright © 2007 by Adam Webber Chapter Ten: Grammars.
Flexible Budgets and Performance Analysis
Analyzing Genes and Genomes
Types of selection structures
Lilian Blot CORE ELEMENTS SELECTION & FUNCTIONS Lecture 3 Autumn 2014 TPOP 1.
©Brooks/Cole, 2001 Chapter 12 Derived Types-- Enumerated, Structure and Union.
Essential Cell Biology
Exponents and Radicals
1 Chapter 3:Operators and Expressions| SCP1103 Programming Technique C | Jumail, FSKSM, UTM, 2006 | Last Updated: July 2006 Slide 1 Operators and Expressions.
Intracellular Compartments and Transport
PSSA Preparation.
Essential Cell Biology
Immunobiology: The Immune System in Health & Disease Sixth Edition
Energy Generation in Mitochondria and Chlorplasts
User Defined Functions Lesson 1 CS1313 Fall User Defined Functions 1 Outline 1.User Defined Functions 1 Outline 2.Standard Library Not Enough #1.
1 Programming Languages (CS 550) Mini Language Interpreter Jeremy R. Johnson.
ML Exceptions.1 Standard ML Exceptions. ML Exceptions.2 Exceptions – The Need  An extensive part of the code is error handling  A function can return.
CSE341: Programming Languages Lecture 2 Functions, Pairs, Lists Dan Grossman Winter 2013.
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.
Getting started with ML ML is a functional programming language. ML is statically typed: The types of literals, values, expressions and functions in 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 =
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.
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.
ML: a quasi-functional language with strong typing
CSE 341 Section 5 Winter 2018.
CSE-321 Programming Languages Introduction to Functional Programming
Presentation transcript:

A Third Look At ML 1

Outline More pattern matching Function values and anonymous functions Higher-order functions and currying Predefined higher-order functions 2

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

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

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

Example 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. 6

Generalizes if The two expressions above are equivalent So if - then - else is really just a special case of case if exp 1 then exp 2 else exp 3 case exp 1 of true => exp 2 | false => exp 3 7

Behind the Scenes Expressions using if are actually treated as abbreviations for case expressions This explains some odd SML/NJ error messages: - if 1=1 then 1 else 1.0; Error: types of rules don't agree [literal] earlier rule(s): bool -> int this rule: bool -> real in rule: false => 1.0 8

Outline More pattern matching Function values and anonymous functions Higher-order functions and currying Predefined higher-order functions 9

Predefined Functions When an ML language system starts, there are many predefined variables Some are bound to functions: - ord; val it = fn : char -> int - ~; val it = fn : int -> int 10

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: - val x = ~; val x = fn : int -> int - x 3; val it = ~3 : int 11

Function Values Functions in ML do not have names 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 12

Anonymous Functions Named function: Anonymous function: - 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 13

The fn Syntax 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 These two definitions have the same effect: – fun f x = x + 2 – val f = fn x => x + 2 ::= fn 14

Using Anonymous Functions One simple application: when you need a small function in just one place Without fn : With fn : - 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 15

The op keyword 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 - op *; val it = fn : int * int -> int - quicksort ([1,4,3,2,5], op <); val it = [1,2,3,4,5] : int list 16

Outline More pattern matching Function values and anonymous functions Higher-order functions and currying Predefined higher-order functions 17

Higher-order Functions 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 18

Practice 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 19

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; The general name for this is currying 20

Curried Addition Remember that function application is left- associative So g 2 3 means ((g 2) 3) - 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 21

Advantages No tuples: we get to write g 2 3 instead of f(2,3) But the real advantage: we get to specialize functions for particular initial parameters - val add2 = g 2; val add2 = fn : int -> int - add2 3; val it = 5 : int - add2 10; val it = 12 : int 22

Advantages: Example Like the previous quicksort But now, the comparison function is a first, curried parameter - 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 23

Multiple Curried Parameters Currying generalizes to any number of parameters - 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 24

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

Easier Notation for Currying Instead of writing: fun f a = fn b => a+b; We can just write: fun f a b = a+b; This generalizes for any number of curried arguments - fun f a b c d = a+b+c+d; val f = fn : int -> int -> int -> int -> int 26

Outline More pattern matching Function values and anonymous functions Higher-order functions and currying Predefined higher-order functions 27

Predefined Higher-Order Functions 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 28

The map Function Used to apply a function to every element of a list, and collect a list of results - 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 29

The map Function Is Curried - 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 30

The foldr Function 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 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 31

Examples - 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 32

The foldr Function Is Curried - 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 33

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

The foldl Function To add up all the elements of a list x, we could write foldl (op +) 0 x 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 35

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 * For other operations, it does matter - 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 36

The QuickSort Function (1) fun quicksort(nil) = nil | quicksort(h::t) = let val (low,high) = split(h,t) in append(quicksort(low), (h::quicksort(high))) end and split(x,nil) = (nil, nil) | split(x,(h::t)) = let val (k,m) = split(x,t) in if h < x then ((h::k),m) else (k,(h::m)) end and append (a,b) = b; quicksort [2,5,3,1,4]; val it = [1,2,3,4,5] : int list 37

The QuickSort Function (2) fun quicksort(nil,ord) = nil | quicksort(h::t,ord) = let val (low,high) = split(h,t,ord) in append(quicksort(low), (h::quicksort(high))) end and split(x,nil,ord) = (nil, nil) | split(x,(h::t),ord) = let val (k,m) = split(x,t,ord) in if ord(h,x) then ((h::k),m) else (k,(h::m)) end and append (a,b) = b; quicksort ([2,5,3,1,4], op <); val it = [1,2,3,4,5] : int list quicksort ([2,5,3,1,4], op >); val it = [5,4,3,2,1] : int list 38