Modern Programming Languages, 2nd ed.

Slides:



Advertisements
Similar presentations
Numbers Treasure Hunt Following each question, click on the answer. If correct, the next page will load with a graphic first – these can be used to check.
Advertisements

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.
Writing Pseudocode And Making a Flow Chart A Number Guessing Game
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Chapter 5: Repetition and Loop Statements Problem Solving & Program.
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 + ×
Custom Statutory Programs Chapter 3. Customary Statutory Programs and Titles 3-2 Objectives Add Local Statutory Programs Create Customer Application For.
Haskell user defined types data Temp = Cold|Hot|Warm deriving (Show,Eq, Ord, Enum) -- to enable printing to screen -- comparing for equality -- comparison.
Lecture 15 Linked Lists part 2
Solve Multi-step Equations
REVIEW: Arthropod ID. 1. Name the subphylum. 2. Name the subphylum. 3. Name the order.
Factoring Polynomials
Turing Machines.
Chair of Software Engineering Einführung in die Programmierung Introduction to Programming Prof. Dr. Bertrand Meyer Exercise Session 5.
0 PROGRAMMING IN HASKELL Chapter 5 - List Comprehensions.
More ML Compiling Techniques David Walker. Today More data structures lists More functions More modules.
Linked Lists Chapter 4.
Chapter 24 Lists, Stacks, and Queues
Chapter 1 Object Oriented Programming 1. OOP revolves around the concept of an objects. Objects are created using the class definition. Programming techniques.
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]
1 Lecture 16: Tables and OOP. 2 Tables -- get and put.
Semantic Analysis and Symbol Tables
Modern Programming Languages, 2nd ed.
XML and Databases Exercise Session 3 (courtesy of Ghislain Fourny/ETH)
1 public class Newton { public static double sqrt(double c) { double epsilon = 1E-15; if (c < 0) return Double.NaN; double t = c; while (Math.abs(t - c/t)
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.
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;
A Third Look At ML 1. Outline More pattern matching Function values and anonymous functions Higher-order functions and currying Predefined higher-order.
Kurt Jensen Lars M. Kristensen 1 Coloured Petri Nets Department of Computer Science Coloured Petri Nets Modelling and Validation of Concurrent Systems.
© 2012 National Heart Foundation of Australia. Slide 2.
Adding Up In Chunks.
Analyzing Genes and Genomes
1 Let’s Recapitulate. 2 Regular Languages DFAs NFAs Regular Expressions Regular Grammars.
Chapter 9 Interactive Multimedia Authoring with Flash Introduction to Programming 1.
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.
Pointers and Arrays Chapter 12
Essential Cell Biology
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
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 13 - Exception Handling Outline 13.1 Introduction 13.2 Exception-Handling Overview 13.3 Other.
Topic 16 Sorting Using ADTs to Implement Sorting Algorithms.
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 Decidability continued…. 2 Theorem: For a recursively enumerable language it is undecidable to determine whether is finite Proof: We will reduce the.
Data Structures Using C++ 2E
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.
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,
ML: a quasi-functional language with strong typing Conventional syntax: - val x = 5; (*user input *) val x = 5: int (*system response*) - fun len lis =
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.
Introduction to ML Last time: Basics: integers, Booleans, tuples,... simple functions introduction to data types This time, we continue writing an evaluator.
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.
Chapter SevenModern Programming Languages1 A Second Look At ML.
ML: a quasi-functional language with strong typing
ML Again ( Chapter 7) Patterns Local variable definitions
Presentation transcript:

Modern Programming Languages, 2nd ed. A Second Look At ML Chapter Seven Modern Programming Languages, 2nd ed.

Modern Programming Languages, 2nd ed. Outline Patterns Local variable definitions A sorting example Chapter Seven Modern Programming Languages, 2nd ed.

Two Patterns You Already Know We have seen that ML functions take a single parameter: fun f n = n*n; We have also seen how to specify functions with more than one input by using tuples: fun f (a, b) = a*b; Both n and (a, b) are patterns. The n matches and binds to any argument, while (a,b) matches any 2-tuple and binds a and b to its components Chapter Seven Modern Programming Languages, 2nd ed.

Underscore As A Pattern - fun f _ = "yes"; val f = fn : 'a -> string - f 34.5; val it = "yes" : string - f []; The underscore can be used as a pattern It matches anything, but does not bind it to a variable Preferred to: fun f x = "yes"; Chapter Seven Modern Programming Languages, 2nd ed.

Modern Programming Languages, 2nd ed. Constants As Patterns - fun f 0 = "yes"; Warning: match nonexhaustive 0 => ... val f = fn : int -> string - f 0; val it = "yes" : string Any constant of an equality type can be used as a pattern But not: fun f 0.0 = "yes"; Chapter Seven Modern Programming Languages, 2nd ed.

Modern Programming Languages, 2nd ed. Non-Exhaustive Match In that last example, the type of f was int -> string, but with a “match non-exhaustive” warning Meaning: f was defined using a pattern that didn’t cover all the domain type (int) So you may get runtime errors like this: - f 0; val it = "yes" : string - f 1; uncaught exception nonexhaustive match failure Chapter Seven Modern Programming Languages, 2nd ed.

Lists Of Patterns As Patterns - fun f [a,_] = a; Warning: match nonexhaustive a :: _ :: nil => ... val f = fn : 'a list -> 'a - f [#"f",#"g"]; val it = #"f" : char You can use a list of patterns as a pattern This example matches any list of length 2 It treats a and _ as sub-patterns, binding a to the first list element Chapter Seven Modern Programming Languages, 2nd ed.

Cons Of Patterns As A Pattern - fun f (x::xs) = x; Warning: match nonexhaustive x :: xs => ... val f = fn : 'a list -> 'a - f [1,2,3]; val it = 1 : int You can use a cons of patterns as a pattern x::xs matches any non-empty list, and binds x to the head and xs to the tail Parens around x::xs are for precedence Chapter Seven Modern Programming Languages, 2nd ed.

Modern Programming Languages, 2nd ed. ML Patterns So Far A variable is a pattern that matches anything, and binds to it A _ is a pattern that matches anything A constant (of an equality type) is a pattern that matches only that constant A tuple of patterns is a pattern that matches any tuple of the right size, whose contents match the sub-patterns A list of patterns is a pattern that matches any list of the right size, whose contents match the sub-patterns A cons (::) of patterns is a pattern that matches any non-empty list whose head and tail match the sub-patterns Chapter Seven Modern Programming Languages, 2nd ed.

Multiple Patterns for Functions - fun f 0 = "zero" = | f 1 = "one"; Warning: match nonexhaustive 0 => ... 1 => ... val f = fn : int -> string; - f 1; val it = "one" : string You can define a function by listing alternate patterns Chapter Seven Modern Programming Languages, 2nd ed.

Modern Programming Languages, 2nd ed. Syntax <fun-def> ::= fun <fun-bodies> ; <fun-bodies> ::= <fun-body> | <fun-body> '|' <fun-bodies> <fun-body> ::= <fun-name> <pattern> = <expression> To list alternate patterns for a function You must repeat the function name in each alternative Chapter Seven Modern Programming Languages, 2nd ed.

Modern Programming Languages, 2nd ed. Overlapping Patterns - fun f 0 = "zero" = | f _ = "non-zero"; val f = fn : int -> string; - f 0; val it = "zero" : string - f 34; val it = "non-zero" : string Patterns may overlap ML uses the first match for a given argument Chapter Seven Modern Programming Languages, 2nd ed.

Pattern-Matching Style These definitions are equivalent: fun f 0 = "zero" | f _ = "non-zero"; fun f n = if n = 0 then "zero" else "non-zero"; But the pattern-matching style usually preferred in ML It often gives shorter and more legible functions Chapter Seven Modern Programming Languages, 2nd ed.

Pattern-Matching Example Original (from Chapter 5): fun fact n = if n = 0 then 1 else n * fact(n-1); Rewritten using patterns: fun fact 0 = 1 | fact n = n * fact(n-1); Chapter Seven Modern Programming Languages, 2nd ed.

Pattern-Matching Example Original (from Chapter 5): fun reverse L = if null L then nil else reverse(tl L) @ [hd L]; Improved using patterns: fun reverse nil = nil | reverse (first::rest) = reverse rest @ [first]; Chapter Seven Modern Programming Languages, 2nd ed.

Modern Programming Languages, 2nd ed. More Examples This structure occurs frequently in recursive functions that operate on lists: one alternative for the base case (nil) and one alternative for the recursive case (first::rest). Adding up all the elements of a list: fun f nil = 0 | f (first::rest) = first + f rest; Counting the true values in a list: fun f nil = 0 | f (true::rest) = 1 + f rest | f (false::rest) = f rest; Chapter Seven Modern Programming Languages, 2nd ed.

Modern Programming Languages, 2nd ed. More Examples Making a new list of integers in which each is one greater than in the original list: fun f nil = nil | f (first::rest) = first+1 :: f rest; Chapter Seven Modern Programming Languages, 2nd ed.

Modern Programming Languages, 2nd ed. A Restriction You can't use the same variable more than once in the same pattern This is not legal: You must use this instead: fun f (a,a) = … for pairs of equal elements | f (a,b) = … for pairs of unequal elements fun f (a,b) = if (a=b) then … for pairs of equal elements else … for pairs of unequal elements Chapter Seven Modern Programming Languages, 2nd ed.

Modern Programming Languages, 2nd ed. The polyEqual Warning - fun eq (a,b) = if a=b then 1 else 0; Warning: calling polyEqual val eq = fn : ''a * ''a -> int - eq (1,3); val it = 0 : int - eq ("abc","abc"); val it = 1 : int Warning for an equality comparison, when the runtime type cannot be resolved OK to ignore: this kind of equality test is inefficient, but can’t always be avoided Chapter Seven Modern Programming Languages, 2nd ed.

Modern Programming Languages, 2nd ed. Patterns Everywhere - val (a,b) = (1,2.3); val a = 1 : int val b = 2.3 : real - val a::b = [1,2,3,4,5]; Warning: binding not exhaustive a :: b = ... val b = [2,3,4,5] : int list Patterns are not just for function definition Here we see that you can use them in a val More ways to use patterns, later Chapter Seven Modern Programming Languages, 2nd ed.

Modern Programming Languages, 2nd ed. Outline Patterns Local variable definitions A sort example Chapter Seven Modern Programming Languages, 2nd ed.

Local Variable Definitions When you use val at the top level to define a variable, it is visible from that point forward There is a way to restrict the scope of definitions: the let expression <let-exp> ::= let <definitions> in <expression> end Chapter Seven Modern Programming Languages, 2nd ed.

Modern Programming Languages, 2nd ed. Example with let - let val x = 1 val y = 2 in x+y end; val it = 3 : int; - x; Error: unbound variable or constructor: x The value of a let expression is the value of the expression in the in part Variables defined with val between the let and the in are visible only from the point of declaration up to the end Chapter Seven Modern Programming Languages, 2nd ed.

Proper Indentation for let let val x = 1 val y = 2 in x+y end For readability, use multiple lines and indent let expressions like this Some ML programmers put a semicolon after each val declaration in a let Chapter Seven Modern Programming Languages, 2nd ed.

Long Expressions with let fun days2ms days = let val hours = days * 24.0 val minutes = hours * 60.0 val seconds = minutes * 60.0 in seconds * 1000.0 end; The let expression allows you to break up long expressions and name the pieces This can make code more readable Chapter Seven Modern Programming Languages, 2nd ed.

Modern Programming Languages, 2nd ed. Patterns with let fun halve nil = (nil, nil) | halve [a] = ([a], nil) | halve (a::b::cs) = let val (x, y) = halve cs in (a::x, b::y) end; By using patterns in the declarations of a let, you can get easy “deconstruction” This example takes a list argument and returns a pair of lists, with half in each Chapter Seven Modern Programming Languages, 2nd ed.

Again, Without Good Patterns let val halved = halve cs val x = #1 halved val y = #2 halved in (a::x, b::y) end; In general, if you find yourself using # to extract an element from a tuple, think twice Pattern matching usually gives a better solution Chapter Seven Modern Programming Languages, 2nd ed.

Modern Programming Languages, 2nd ed. halve At Work - fun halve nil = (nil, nil) = | halve [a] = ([a], nil) = | halve (a::b::cs) = = let = val (x, y) = halve cs = in = (a::x, b::y) = end; val halve = fn : 'a list -> 'a list * 'a list - halve [1]; val it = ([1],[]) : int list * int list - halve [1,2]; val it = ([1],[2]) : int list * int list - halve [1,2,3,4,5,6]; val it = ([1,3,5],[2,4,6]) : int list * int list Chapter Seven Modern Programming Languages, 2nd ed.

Modern Programming Languages, 2nd ed. Outline Patterns Local variable definitions A sort example Chapter Seven Modern Programming Languages, 2nd ed.

Modern Programming Languages, 2nd ed. Merge Sort The halve function divides a list into two nearly-equal parts This is the first step in a merge sort For practice, we will look at the rest Chapter Seven Modern Programming Languages, 2nd ed.

Modern Programming Languages, 2nd ed. Example: Merge fun merge (nil, ys) = ys | merge (xs, nil) = xs | merge (x::xs, y::ys) = if (x < y) then x :: merge(xs, y::ys) else y :: merge(x::xs, ys); Merges two sorted lists Note: default type for < is int Chapter Seven Modern Programming Languages, 2nd ed.

Modern Programming Languages, 2nd ed. Merge At Work - fun merge (nil, ys) = ys = | merge (xs, nil) = xs = | merge (x::xs, y::ys) = = if (x < y) then x :: merge(xs, y::ys) = else y :: merge(x::xs, ys); val merge = fn : int list * int list -> int list - merge ([2],[1,3]); val it = [1,2,3] : int list - merge ([1,3,4,7,8],[2,3,5,6,10]); val it = [1,2,3,3,4,5,6,7,8,10] : int list Chapter Seven Modern Programming Languages, 2nd ed.

Modern Programming Languages, 2nd ed. Example: Merge Sort fun mergeSort nil = nil | mergeSort [a] = [a] | mergeSort theList = let val (x, y) = halve theList in merge(mergeSort x, mergeSort y) end; Merge sort of a list Type is int list -> int list, because of type already found for merge Chapter Seven Modern Programming Languages, 2nd ed.

Modern Programming Languages, 2nd ed. Merge Sort At Work - fun mergeSort nil = nil = | mergeSort [a] = [a] = | mergeSort theList = = let = val (x, y) = halve theList = in = merge(mergeSort x, mergeSort y) = end; val mergeSort = fn : int list -> int list - mergeSort [4,3,2,1]; val it = [1,2,3,4] : int list - mergeSort [4,2,3,1,5,3,6]; val it = [1,2,3,3,4,5,6] : int list Chapter Seven Modern Programming Languages, 2nd ed.

Nested Function Definitions You can define local functions, just like local variables, using a let You should do it for helper functions that you don't think will be useful by themselves We can hide halve and merge from the rest of the program this way Another potential advantage: inner function can refer to variables from outer one (as we will see in Chapter 12) Chapter Seven Modern Programming Languages, 2nd ed.

Modern Programming Languages, 2nd ed. (* Sort a list of integers. *) fun mergeSort nil = nil | mergeSort [e] = [e] | mergeSort theList = let (* From the given list make a pair of lists * (x,y), where half the elements of the * original are in x and half are in y. *) fun halve nil = (nil, nil) | halve [a] = ([a], nil) | halve (a::b::cs) = let val (x, y) = halve cs in (a::x, b::y) end; continued… Chapter Seven Modern Programming Languages, 2nd ed.

Modern Programming Languages, 2nd ed. (* Merge two sorted lists of integers into * a single sorted list. *) fun merge (nil, ys) = ys | merge (xs, nil) = xs | merge (x::xs, y::ys) = if (x < y) then x :: merge(xs, y::ys) else y :: merge(x::xs, ys); val (x, y) = halve theList in merge(mergeSort x, mergeSort y) end; Chapter Seven Modern Programming Languages, 2nd ed.

Modern Programming Languages, 2nd ed. Commenting Everything between (* and *) in ML is a comment You should (at least) comment every function definition, as in any language what parameters does it expect what function does it compute how does it do it (if non-obvious) etc. Chapter Seven Modern Programming Languages, 2nd ed.