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;

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

Chapter 25 Lists, Stacks, Queues, and Priority Queues
1
Chapter 7 Constructors and Other Tools. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-2 Learning Objectives Constructors Definitions.
Chapter 17 Linked Data Structures. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives Nodes and Linked Lists Creating,
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 + ×
Process a Customer Chapter 2. Process a Customer 2-2 Objectives Understand what defines a Customer Learn how to check for an existing Customer Learn how.
Custom Statutory Programs Chapter 3. Customary Statutory Programs and Titles 3-2 Objectives Add Local Statutory Programs Create Customer Application For.
1 10 pt 15 pt 20 pt 25 pt 5 pt 10 pt 15 pt 20 pt 25 pt 5 pt 10 pt 15 pt 20 pt 25 pt 5 pt 10 pt 15 pt 20 pt 25 pt 5 pt 10 pt 15 pt 20 pt 25 pt 5 pt BlendsDigraphsShort.
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.
Break Time Remaining 10:00.
Turing Machines.
Table 12.1: Cash Flows to a Cash and Carry Trading Strategy.
PP Test Review Sections 6-1 to 6-6
More ML Compiling Techniques David Walker. Today More data structures lists More functions More modules.
Chapter 24 Lists, Stacks, and Queues
Data Structures Part 2 Stacks, Queues, Trees, and Graphs Briana B. Morrison CSE 1302C Spring 2010.
Modern Programming Languages, 2nd ed.
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]
Bright Futures Guidelines Priorities and Screening Tables
Semantic Analysis and Symbol Tables
Modern Programming Languages, 2nd ed.
Understanding class definitions Looking inside classes 5.0.
Bellwork Do the following problem on a ½ sheet of paper and turn in.
Exarte Bezoek aan de Mediacampus Bachelor in de grafische en digitale media April 2014.
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.
Copyright © 2012, Elsevier Inc. All rights Reserved. 1 Chapter 7 Modeling Structure with Blocks.
1 RA III - Regional Training Seminar on CLIMAT&CLIMAT TEMP Reporting Buenos Aires, Argentina, 25 – 27 October 2006 Status of observing programmes in RA.
Basel-ICU-Journal Challenge18/20/ Basel-ICU-Journal Challenge8/20/2014.
1..
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.
CONTROL VISION Set-up. Step 1 Step 2 Step 3 Step 5 Step 4.
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 10 pt 15 pt 20 pt 25 pt 5 pt 10 pt 15 pt 20 pt 25 pt 5 pt 10 pt 15 pt 20 pt 25 pt 5 pt 10 pt 15 pt 20 pt 25 pt 5 pt 10 pt 15 pt 20 pt 25 pt 5 pt Synthetic.
1 hi at no doifpi me be go we of at be do go hi if me no of pi we Inorder Traversal Inorder traversal. n Visit the left subtree. n Visit the node. n Visit.
Analyzing Genes and Genomes
Types of selection structures
©Brooks/Cole, 2001 Chapter 12 Derived Types-- Enumerated, Structure and Union.
Essential Cell Biology
PSSA Preparation.
Essential Cell Biology
Immunobiology: The Immune System in Health & Disease Sixth Edition
Physics for Scientists & Engineers, 3rd Edition
Energy Generation in Mitochondria and Chlorplasts
Murach’s OS/390 and z/OS JCLChapter 16, Slide 1 © 2002, Mike Murach & Associates, Inc.
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.
Chapter 9: Using Classes and Objects. Understanding Class Concepts Types of classes – Classes that are only application programs with a Main() method.
ML Datatypes.1 Standard ML Data types. ML Datatypes.2 Concrete Datatypes  The datatype declaration creates new types  These are concrete data types,
Chapter ElevenModern Programming Languages1 A Fourth Look At ML.
A Fourth Look At ML Chapter 11 Type-Safe Data Structures Chapter ElevenModern Programming Languages1.
A Fourth Look At ML Chapter ElevenModern Programming Languages, 2nd ed.1.
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.
Introduction to ML Last time: Basics: integers, Booleans, tuples,... simple functions introduction to data types This time, we continue writing an evaluator.
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
CSE-321 Programming Languages Introduction to Functional Programming
Presentation transcript:

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; datatype 'element list = nil | :: of 'element * 'element list 2

Outline Enumerations Data constructors with parameters Type constructors with parameters Recursively defined type constructors Farewell to ML 3

Defining Your Own Types New types can be defined using the keyword datatype These declarations define both: – type constructors for making new (possibly polymorphic) types – data constructors for making values of those new types 4

- datatype day = Mon | Tue | Wed | Thu | Fri | Sat | Sun; datatype day = Fri | Mon | Sat | Sun | Thu | Tue | Wed - fun isWeekDay x = not (x = Sat orelse x = Sun); val isWeekDay = fn : day -> bool - isWeekDay Mon; val it = true : bool - isWeekDay Sat; val it = false : bool day is the new type constructor and Mon, Tue, etc. are the new data constructors Why “constructors”? In a moment we will see how both can have parameters… Example 5

The type constructor day takes no parameters: it is not polymorphic, there is only one day type The data constructors Mon, Tue, etc. take no parameters: they are constant values of the day type Capitalize the names of data constructors - datatype day = Mon | Tue | Wed | Thu | Fri | Sat | Sun; datatype day = Fri | Mon | Sat | Sun | Thu | Tue | Wed No Parameters 6

ML is strict about these new types, just as you would expect Unlike C enum, no implementation details are exposed to the programmer - datatype flip = Heads | Tails; datatype flip = Heads | Tails - fun isHeads x = (x = Heads); val isHeads = fn : flip -> bool - isHeads Tails; val it = false : bool - isHeads Mon; Error: operator and operand don't agree [tycon mismatch] operator domain: flip operand: day Strict Typing 7

You can use the data constructors in patterns In this simple case, they are like constants But we will see more general cases next fun isWeekDay Sat = false | isWeekDay Sun = false | isWeekDay _ = true; Data Constructors In Patterns 8

Outline Enumerations Data constructors with parameters Type constructors with parameters Recursively defined type constructors Farewell to ML 9

Wrappers You can add a parameter of any type to a data constructor, using the keyword of : datatype exint = Value of int | PlusInf | MinusInf; In effect, such a constructor is a wrapper that contains a data item of the given type PlusInf Value 36 MinusInfValue 26 Value 38 Some things of type exint : 10

Value is a data constructor that takes a parameter: the value of the int to store It looks like a function that takes an int and returns an exint containing that int - datatype exint = Value of int | PlusInf | MinusInf; datatype exint = MinusInf | PlusInf | Value of int - PlusInf; val it = PlusInf : exint - MinusInf; val it = MinusInf : exint - Value; val it = fn : int -> exint - Value 3; val it = Value 3 : exint 11

Value 5 is an exint It is not an int, though it contains one How can we get the int out again? By pattern matching… - val x = Value 5; val x = Value 5 : exint - x+x; Error: overloaded variable not defined at type symbol: + type: exint A Value Is Not An int 12

To recover a data constructor’s parameters, use pattern matching So Value is no ordinary function: ordinary functions can't be pattern-matched this way - val (Value y) = x; Warning: binding not exhaustive Value y =... val y = 5 : int Patterns With Data Constructors 13

An Exhaustive Pattern Like most uses of the match construct, you get a warning if it is not exhaustive An exint can be a PlusInf, a MinusInf, or a Value This one says what to do in all cases - val s = case x of = PlusInf => "infinity" | = MinusInf => "-infinity" | = Value y => Int.toString y; val s = "5" : string 14

Pattern-matching function definitions are especially important when working with your own datatypes - fun square PlusInf = PlusInf = | square MinusInf = PlusInf = | square (Value x) = Value (x*x); val square = fn : exint -> exint - square MinusInf; val it = PlusInf : exint - square (Value 3); val it = Value 9 : exint Pattern-Matching Function 15

Exception Handling (A Peek) Patterns are also used in ML for exception handling, as in this example - fun square PlusInf = PlusInf = | square MinusInf = PlusInf = | square (Value x) = Value (x*x) = handle Overflow => PlusInf; val square = fn : exint -> exint - square (Value 10000); val it = Value : exint - square (Value ); val it = PlusInf : exint 16

Outline Enumerations Data constructors with parameters Type constructors with parameters Recursively defined type constructors Farewell to ML 17

Type Constructors With Parameters Type constructors can also use parameters: datatype 'a option = NONE | SOME of 'a; The parameters of a type constructor are type variables, which are used in the data constructors The result: a new polymorphic type NONE SOME "Hello" Values of type string option SOME "world" NONE SOME 1.5 Values of type real option SOME

Type constuctor parameter comes before the type constructor name: datatype 'a option = NONE | SOME of 'a; We have types 'a option and int option, just like 'a list and int list - SOME 4; val it = SOME 4 : int option - SOME 1.2; val it = SOME 1.2 : real option - SOME "pig"; val it = SOME "pig" : string option Parameter Before Name 19

Uses For option Predefined type constructor in ML Used by predefined functions (or your own) when the result is not always defined - fun optdiv a b = = if b = 0 then NONE else SOME (a div b); val optdiv = fn : int -> int -> int option - optdiv 7 2; val it = SOME 3 : int option - optdiv 7 0; val it = NONE : int option 20

An 'x bunch is either a thing of type 'x, or a list of things of type 'x As usual, ML infers types: Longer Example: bunch datatype 'x bunch = One of 'x | Group of 'x list; - One 1.0; val it = One 1.0 : real bunch - Group [true,false]; val it = Group [true,false] : bool bunch 21

ML can infer bunch types, but does not always have to resolve them, just as with list types - fun size (One _) = 1 = | size (Group x) = length x; val size = fn : 'a bunch -> int - size (One 1.0); val it = 1 : int - size (Group [true,false]); val it = 2 : int Example: Polymorphism 22

Example: No Polymorphism We applied the + operator (through foldr ) to the list elements So ML knows the parameter type must be int bunch - fun sum (One x) = x = | sum (Group xlist) = foldr op + 0 xlist; val sum = fn : int bunch -> int - sum (One 5); val it = 5 : int - sum (Group [1,2,3]); val it = 6 : int 23

Outline Enumerations Data constructors with parameters Type constructors with parameters Recursively defined type constructors Farewell to ML 24

Recursively Defined Type Constructors The type constructor being defined may be used in its own data constructors: datatype intlist = INTNIL | INTCONS of int * intlist; Some values of type intlist : 25

- INTNIL; val it = INTNIL : intlist - INTCONS (1,INTNIL); val it = INTCONS (1,INTNIL) : intlist - INTCONS (1,INTCONS(2,INTNIL)); val it = INTCONS (1,INTCONS (2,INTNIL)) : intlist Constructing Those Values 26

A length function Much like you would write for native lists Except, of course, that native lists are not always lists of integers… fun intlistLength INTNIL = 0 | intlistLength (INTCONS(_,tail)) = 1 + (intListLength tail); fun listLength nil = 0 | listLength (_::tail) = 1 + (listLength tail); An intlist Length Function 27

Parametric List Type A parametric list type, almost like the predefined list ML handles type inference in the usual way: datatype 'element mylist = NIL | CONS of 'element * 'element mylist; - CONS(1.0, NIL); val it = CONS (1.0,NIL) : real mylist - CONS(1, CONS(2, NIL)); val it = CONS (1,CONS (2,NIL)) : int mylist 28

This now works almost exactly like the predefined list type constructor Of course, to add up a list you would use foldr … fun myListLength NIL = 0 | myListLength (CONS(_,tail)) = 1 + myListLength(tail); Some mylist Functions fun addup NIL = 0 | addup (CONS(head,tail)) = head + addup tail; 29

Definition of a function like foldr that works on 'a mylist Can now add up an int mylist x with: myfoldr (op +) 0 x One remaining difference: :: is an operator and CONS is not fun myfoldr f c NIL = c | myfoldr f c (CONS(a,b)) = f(a, myfoldr f c b); A foldr For mylist 30

Defining Operators (A Peek) ML allows new operators to be defined Like this: - infixr 5 CONS; infixr 5 CONS - 1 CONS 2 CONS NIL; val it = 1 CONS 2 CONS NIL : int mylist 31

datatype 'data tree = Empty | Node of 'data tree * 'data * 'data tree; Some values of type int tree : Polymorphic Binary Tree 32

- val treeEmpty = Empty; val treeEmpty = Empty : 'a tree - val tree2 = Node(Empty,2,Empty); val tree2 = Node (Empty,2,Empty) : int tree - val tree123 = Node(Node(Empty,1,Empty), = 2, = Node(Empty,3,Empty)); Constructing Those Values 33

Increment All Elements fun incall Empty = Empty | incall (Node(x,y,z)) = Node(incall x, y+1, incall z); - incall tree123; val it = Node (Node (Empty,2,Empty), 3, Node (Empty,4,Empty)) : int tree 34

Add Up The Elements fun sumall Empty = 0 | sumall (Node(x,y,z)) = sumall x + y + sumall z; - sumall tree123; val it = 6 : int 35

Convert To List (Polymorphic) fun listall Empty = nil | listall (Node(x,y,z)) = listall y :: listall z; - listall tree123; val it = [1,2,3] : int list 36

Tree Search fun isintree x Empty = false | isintree x (Node(left,y,right)) = x=y orelse isintree x left orelse isintree x right; - isintree 4 tree123; val it = false : bool - isintree 3 tree123; val it = true : bool 37

Outline Enumerations Data constructors with parameters Type constructors with parameters Recursively defined type constructors Farewell to ML 38

That's All There is, of course, a lot more A few words about the parts we skipped: – records (like tuples with named fields) – arrays, with elements that can be altered – references, for values that can be altered – exception handling 39

More Parts We Skipped – support for encapsulation and data hiding: structures: collections of datatypes, functions, etc. signatures: interfaces for structures functors: like functions that operate on structures, allowing type variables and other things to be instantiated across a whole structure 40

More Parts We Skipped – API: the standard basis predefined functions, types, etc. Some at the top level but most in structures: Int.maxInt, Real.Math.sqrt, List.nth, etc. 41

More Parts We Skipped – eXene: an ML library for applications that work in the X window system – the Compilation Manager for building large ML projects Other dialects besides Standard ML – OCaml – Concurrent ML (CML) extensions 42

Functional Languages ML supports a function-oriented style of programming If you like that style, there are many other languages to explore, like Lisp and Haskell 43