Chapter SevenModern Programming Languages1 A Second Look At ML.

Slides:



Advertisements
Similar presentations
More ML Compiling Techniques David Walker. Today More data structures lists More functions More modules.
Advertisements

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]
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.
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.
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,
Control Structures Any mechanism that departs from straight-line execution: –Selection: if-statements –Multiway-selection: case statements –Unbounded iteration:
ML Exceptions.1 Standard ML Exceptions. ML Exceptions.2 Exceptions – The Need  An extensive part of the code is error handling  A function F can return.
Getting started with ML ML is a functional programming language. ML is statically typed: The types of literals, values, expressions and functions in a.
Functional Programming. Pure Functional Programming Computation is largely performed by applying functions to values. The value of an expression depends.
ML: a quasi-functional language with strong typing Conventional syntax: - val x = 5; (*user input *) val x = 5: int (*system response*) - fun len lis =
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.
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.
0 PROGRAMMING IN HASKELL Chapter 4 - Defining Functions.
ML: a quasi-functional language with strong typing Conventional syntax: - val x = 5; (*user input *) val x = 5: int (*system response*) - fun len lis =
CS 330 Programming Languages 11 / 20 / 2007 Instructor: Michael Eckmann.
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.
0 PROGRAMMING IN HASKELL Chapter 6 - Recursive Functions Most of this should be review for you.
0 PROGRAMMING IN HASKELL Chapter 6 - Recursive Functions.
Functional programming: LISP Originally developed for symbolic computing First interactive, interpreted language Dynamic typing: values have types, variables.
1 Functional Programming and ML. 2 What’s wrong with Imperative Languages? State State Introduces context sensitivity Introduces context sensitivity Harder.
Type Inference: CIS Seminar, 11/3/2009 Type inference: Inside the Type Checker. A presentation by: Daniel Tuck.
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,
Haskell Chapter 3, Part I. Pattern Matching  Pattern matching with tuples  Pattern matching with list comprehensions  As-patterns.
CS 2104 : Prog. Lang. Concepts. Functional Programming I Lecturer : Dr. Abhik Roychoudhury School of Computing From Dr. Khoo Siau Cheng’s lecture notes.
Functional Programming Element of Functional Programming.
Chapter TwelveModern Programming Languages1 Memory Locations For Variables.
PrasadCS7761 Haskell Data Types/ADT/Modules Type/Class Hierarchy Lazy Functional Language.
ML Datatypes.1 Standard ML Data types. ML Datatypes.2 Concrete Datatypes  The datatype declaration creates new types  These are concrete data types,
0 REVIEW OF HASKELL A lightening tour in 45 minutes.
0 PROGRAMMING IN HASKELL Chapter 7 - Defining Functions, List Comprehensions.
10/16/2015IT 3271 All about binding n Variables are bound (dynamically) to values n values must be stored somewhere in the memory. Memory Locations for.
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.
Introduction to Functional Programming and ML CS 331 Principles of Programming Languages.
Chapter 9: Functional Programming in a Typed Language.
Functional Programming With examples in F#. Pure Functional Programming Functional programming involves evaluating expressions rather than executing commands.
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.
F28PL1 Programming Languages Lecture 13: Standard ML 3.
A Third Look At ML Chapter NineModern Programming Languages, 2nd ed.1.
1 CS 457/557: Functional Languages Lists and Algebraic Datatypes Mark P Jones Portland State University.
Recursion on Lists Lecture 5, Programmeringsteknik del A.
0 PROGRAMMING IN HASKELL Chapter 4 - Defining Functions.
Lee CSCE 314 TAMU 1 CSCE 314 Programming Languages Haskell: More on Functions and List Comprehensions Dr. Hyunyoung Lee.
A FIRST LOOK AT ML Chapter Five Modern Programming Languages 1.
0 PROGRAMMING IN HASKELL Based on lecture notes by Graham Hutton The book “Learn You a Haskell for Great Good” (and a few other sources) Odds and Ends,
Cs776(Prasad)L6sml971 SML-97 Specifics SML/NJ 110.
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.
The for Statement A most versatile loop
ML: a quasi-functional language with strong typing
ML Again ( Chapter 7) Patterns Local variable definitions
A lightening tour in 45 minutes
PROGRAMMING IN HASKELL
Memory Locations For Variables
PROGRAMMING IN HASKELL
CSE 341 Lecture 3 let expressions; pattern matching Ullman
Objective caml Daniel Jackson MIT Lab for Computer Science 6898: Advanced Topics in Software Design March 18, 2002.
CSCE 314: Programming Languages Dr. Dylan Shell
PROGRAMMING IN HASKELL
CSE-321 Programming Languages Introduction to Functional Programming
PROGRAMMING IN HASKELL
Presentation transcript:

Chapter SevenModern Programming Languages1 A Second Look At ML

Chapter SevenModern Programming Languages2 Outline n Patterns n Local variable definitions n A sorting example

Chapter SevenModern Programming Languages3 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 SevenModern Programming Languages4 - fun f _ = "yes"; val f = fn : 'a -> string - f 34.5; val it = "yes" : string - f []; val it = "yes" : string Underscore As A Pattern n The underscore can be used as a pattern n It matches anything, but does not bind it to a variable Preferred to: fun f x = "yes";

Chapter SevenModern Programming Languages5 - fun f 0 = "yes"; Warning: match nonexhaustive 0 =>... val f = fn : int -> string - f 0; val it = "yes" : string Constants As Patterns n Any constant of an equality type can be used as a pattern But not: fun f 0.0 = "yes";

Chapter SevenModern Programming Languages6 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 ) n So you may get runtime errors like this: - f 0; val it = "yes" : string - f 1; uncaught exception nonexhaustive match failure

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

Chapter SevenModern Programming Languages8 Cons Of Patterns As A Pattern n 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 - fun f (x::xs) = x; Warning: match nonexhaustive x :: xs =>... val f = fn : 'a list -> 'a - f [1,2,3]; val it = 1 : int

Chapter SevenModern Programming Languages9 ML Patterns So Far n A variable is a pattern that matches anything, and binds to it A _ is a pattern that matches anything n A constant (of an equality type) is a pattern that matches only that constant n A tuple of patterns is a pattern that matches any tuple of the right size, whose contents match the sub-patterns n 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 SevenModern Programming Languages10 Multiple Patterns for Functions n You can define a function by listing alternate patterns - fun f 0 = "zero" = | f 1 = "one"; Warning: match nonexhaustive 0 =>... 1 =>... val f = fn : int -> string; - f 1; val it = "one" : string

Chapter SevenModern Programming Languages11 Syntax n To list alternate patterns for a function n You must repeat the function name in each alternative ::= fun ; ::= | '|' ::= =

Chapter SevenModern Programming Languages12 Overlapping Patterns n Patterns may overlap n ML uses the first match for a given argument - 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

Chapter SevenModern Programming Languages13 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"; n But the pattern-matching style usually preferred in ML n It often gives shorter and more legible functions

Chapter SevenModern Programming Languages14 Pattern-Matching Example fun fact n = if n = 0 then 1 else n * fact(n-1); Original (from Chapter 5): Rewritten using patterns: fun fact 0 = 1 | fact n = n * fact(n-1);

Chapter SevenModern Programming Languages15 Pattern-Matching Example fun reverse L = if null L then nil else reverse(tl [hd L]; Original (from Chapter 5): Improved using patterns: fun reverse nil = nil | reverse (first::rest) = reverse [first];

Chapter SevenModern Programming Languages16 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 SevenModern Programming Languages17 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 SevenModern Programming Languages18 A Restriction n You can't use the same variable more than once in the same pattern n This is not legal: n 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 SevenModern Programming Languages19 Patterns Everywhere n Patterns are not just for function definition Here we see that you can use them in a val n More ways to use patterns, later - 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 a = 1 : int val b = [2,3,4,5] : int list

Chapter SevenModern Programming Languages20 Outline n Patterns n Local variable definitions n A sort example

Chapter SevenModern Programming Languages21 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 in end

Chapter SevenModern Programming Languages22 Example with let 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 - let val x = 1 val y = 2 in x+y end; val it = 3 : int; - x; Error: unbound variable or constructor: x

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

Chapter SevenModern Programming Languages24 Long Expressions with let The let expression allows you to break up long expressions and name the pieces n This can make code more readable fun days2ms days = let val hours = days * 24.0 val minutes = hours * 60.0 val seconds = minutes * 60.0 in seconds * end;

Chapter SevenModern Programming Languages25 Patterns with let By using patterns in the declarations of a let, you can get easy “deconstruction” n This example takes a list argument and returns a pair of lists, with half in each 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;

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

Chapter SevenModern Programming Languages27 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 SevenModern Programming Languages28 Outline n Patterns n Local variable definitions n A sort example

Chapter SevenModern Programming Languages29 Merge Sort The halve function divides a list into two nearly-equal parts n This is the first step in a merge sort n For practice, we will look at the rest

Chapter SevenModern Programming Languages30 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); Example: Merge n Merges two sorted lists Note: default type for < is int

Chapter SevenModern Programming Languages31 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 SevenModern Programming Languages32 fun mergeSort nil = nil | mergeSort [a] = [a] | mergeSort theList = let val (x, y) = halve theList in merge(mergeSort x, mergeSort y) end; Example: Merge Sort n Merge sort of a list Type is int list -> int list, because of type already found for merge

Chapter SevenModern Programming Languages33 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 SevenModern Programming Languages34 Nested Function Definitions You can define local functions, just like local variables, using a let n 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 n Another potential advantage: inner function can refer to variables from outer one (as we will see in Chapter 12)

Chapter SevenModern Programming Languages35 (* 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 SevenModern Programming Languages36 (* 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 SevenModern Programming Languages37 Commenting Everything between (* and *) in ML is a comment n 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.