Chapter ElevenModern Programming Languages1 A Fourth 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.
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 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.
CSE341: Programming Languages Lecture 2 Functions, Pairs, Lists Dan Grossman Winter 2013.
F28PL1 Programming Languages Lecture 14: Standard ML 4.
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 Datatypes.1 Standard ML Data types. ML Datatypes.2 Concrete Data  Consists of constructions that can be inspected, taken apart, or joined to form.
Getting started with ML ML is a functional programming language. ML is statically typed: The types of literals, values, expressions and functions in a.
Overview of Previous Lesson(s) Over View  Front end analyzes a source program and creates an intermediate representation from which the back end generates.
Object Orientation Chapter SixteenModern Programming Languages, 2nd ed.1 Spring 2012.
Object Orientation Chapter SixteenModern Programming Languages, 2nd ed.1.
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 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.
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.
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.
Polymorphism Chapter EightModern Programming Languages1.
Chapter EightModern Programming Languages1 Polymorphism.
Polymorphism Chapter EightModern Programming Languages1.
Defining new types of data. Defining New Datatypes Ability to add new datatypes in a programming language is important. Kinds of datatypes – enumerated.
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.
Last Time Introduction Course Logistics Introduction to ML Base Types Tuples and Records Functions & Polymorphism See Harper ’ s Intro to ML.
1 Functional Programming and ML. 2 What’s wrong with Imperative Languages? State State Introduces context sensitivity Introduces context sensitivity Harder.
CSE 341 Lecture 10 more about data types; nullable types; option Ullman ; slides created by Marty Stepp
CS 2104 : Prog. Lang. Concepts. Functional Programming I Lecturer : Dr. Abhik Roychoudhury School of Computing From Dr. Khoo Siau Cheng’s lecture notes.
CS235 Languages and Automata Department of Computer Science Wellesley College Introduction to Standard ML Wednesday, September 23, 2009 Reading: Beginning.
ML Datatypes.1 Standard ML Data types. ML Datatypes.2 Concrete Datatypes  The datatype declaration creates new types  These are concrete data types,
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.
Introduction to Functional Programming and ML CS 331 Principles of Programming Languages.
Chapter 9: Functional Programming in a Typed Language.
Lee CSCE 314 TAMU 1 CSCE 314 Programming Languages Haskell: Types and Classes Dr. Hyunyoung Lee.
Functional Programming With examples in F#. Pure Functional Programming Functional programming involves evaluating expressions rather than executing commands.
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.
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.
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,
1.SML Docs Standard Basis 2.First-Class Functions Anonymous Style Points Higher-Order 3.Examples Agenda.
7/7/20161 Programming Languages and Compilers (CS 421) Dennis Griffith 0207 SC, UIUC Based in part on slides by Mattox.
Principles of programming languages 12: Functional programming
ML: a quasi-functional language with strong typing
Haskell Chapter 2.
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
Functions, Patterns and Datatypes
Functions, Patterns and Datatypes
Types and Classes in Haskell
Functions, Patterns and Datatypes
CSE-321 Programming Languages Introduction to Functional Programming
Functions, Patterns and Datatypes
CSE-321 Programming Languages Introduction to Functional Programming
PROGRAMMING IN HASKELL
Functions, Patterns and Datatypes
Review Previously User-defined data types: records, variants
Presentation transcript:

Chapter ElevenModern Programming Languages1 A Fourth Look At ML

Chapter ElevenModern Programming Languages2 Type Definitions n Predefined, but not primitive in ML: n Type constructor for lists: n Defined for ML in ML datatype bool = true | false; datatype 'element list = nil | :: of 'element * 'element list

Chapter ElevenModern Programming Languages3 Outline n Enumerations n Data constructors with parameters n Type constructors with parameters n Recursively defined type constructors n Farewell to ML

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

Chapter ElevenModern Programming Languages5 - 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 n Why “constructors”? In a moment we will see how both can have parameters… Example

Chapter ElevenModern Programming Languages6 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 n 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

Chapter ElevenModern Programming Languages7 n 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

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

Chapter ElevenModern Programming Languages9 Outline n Enumerations n Data constructors with parameters n Type constructors with parameters n Recursively defined type constructors n Farewell to ML

Chapter ElevenModern Programming Languages10 Wrappers You can add a parameter of any type to a data constructor, using the keyword of : datatype exint = Value of int | PlusInf | MinusInf; n 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 :

Chapter ElevenModern Programming Languages11 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

Chapter ElevenModern Programming Languages12 Value 5 is an exint It is not an int, though it contains one How can we get the int out again? n 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

Chapter ElevenModern Programming Languages13 n 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

Chapter ElevenModern Programming Languages14 An Exhaustive Pattern n 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 n 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

Chapter ElevenModern Programming Languages15 n 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

Chapter ElevenModern Programming Languages16 Exception Handling (A Peek) n Patterns are also used in ML for exception handling, as in this example n We’ll see it in Java, but skip it in ML - 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

Chapter ElevenModern Programming Languages17 Outline n Enumerations n Data constructors with parameters n Type constructors with parameters n Recursively defined type constructors n Farewell to ML

Chapter ElevenModern Programming Languages18 Type Constructors With Parameters Type constructors can also use parameters: datatype 'a option = NONE | SOME of 'a; n The parameters of a type constructor are type variables, which are used in the data constructors n 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 123.4

Chapter ElevenModern Programming Languages19 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

Chapter ElevenModern Programming Languages20 Uses For option n Predefined type constructor in ML n 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

Chapter ElevenModern Programming Languages21 An 'x bunch is either a thing of type 'x, or a list of things of type 'x n 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

Chapter ElevenModern Programming Languages22 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

Chapter ElevenModern Programming Languages23 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

Chapter ElevenModern Programming Languages24 Outline n Enumerations n Data constructors with parameters n Type constructors with parameters n Recursively defined type constructors n Farewell to ML

Chapter ElevenModern Programming Languages25 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 :

Chapter ElevenModern Programming Languages26 - 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

Chapter ElevenModern Programming Languages27 n A length function n Much like you would write for native lists n 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

Chapter ElevenModern Programming Languages28 Parametric List Type A parametric list type, almost like the predefined list n 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

Chapter ElevenModern Programming Languages29 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;

Chapter ElevenModern Programming Languages30 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

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

Chapter ElevenModern Programming Languages32 datatype 'data tree = Empty | Node of 'data tree * 'data * 'data tree; Some values of type int tree : Polymorphic Binary Tree

Chapter ElevenModern Programming Languages33 - 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

Chapter ElevenModern Programming Languages34 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

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

Chapter ElevenModern Programming Languages36 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

Chapter ElevenModern Programming Languages37 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

Chapter ElevenModern Programming Languages38 Outline n Enumerations n Data constructors with parameters n Type constructors with parameters n Recursively defined type constructors n Farewell to ML

Chapter ElevenModern Programming Languages39 That's All n That’s all the ML we will see n There is, of course, a lot more n 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

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

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

Chapter ElevenModern Programming Languages42 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 n Other dialects besides Standard ML – OCaml – Concurrent ML (CML) extensions

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