Review Previously User-defined data types: records, variants

Slides:



Advertisements
Similar presentations
Sml2java a source to source translator Justin Koser, Haakon Larsen, Jeffrey Vaughan PLI 2003 DP-COOL.
Advertisements

Types and Programming Languages Lecture 8 Simon Gay Department of Computing Science University of Glasgow 2006/07.
More ML Compiling Techniques David Walker. Today More data structures lists More functions More modules.
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;
ML Datatypes.1 Standard ML Data types. ML Datatypes.2 Concrete Datatypes  The datatype declaration creates new types  These are concrete data types,
Programovací jazyky F# a OCaml Chapter 3. Composing primitive types into data.
0 PROGRAMMING IN HASKELL Chapter 10 - Declaring Types and Classes.
String is a synonym for the type [Char].
ML: a quasi-functional language with strong typing Conventional syntax: - val x = 5; (*user input *) val x = 5: int (*system response*) - fun len lis =
Chapter ElevenModern Programming Languages1 A Fourth Look At ML.
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.
Defining new types of data. Defining New Datatypes Ability to add new datatypes in a programming language is important. Kinds of datatypes – enumerated.
CSE341: Programming Languages Lecture 5 Pattern-Matching Dan Grossman Fall 2011.
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 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.
ML Datatypes.1 Standard ML Data types. ML Datatypes.2 Concrete Datatypes  The datatype declaration creates new types  These are concrete data types,
Lee CSCE 314 TAMU 1 CSCE 314 Programming Languages Haskell: Types and Classes Dr. Hyunyoung Lee.
1 Functional Programming Lecture 6 - Algebraic Data Types.
CSED101 INTRODUCTION TO COMPUTING SUM TYPE 유환조 Hwanjo Yu.
CMSC 330: Organization of Programming Languages Operational Semantics.
More Data Types CSCE 314 Spring CSCE 314 – Programming Studio Defining New Data Types Three ways to define types: 1.type – Define a synonym for.
An introduction to functional programming using Haskell CENG242 –Recitation 1.
CMSC 330: Organization of Programming Languages Object Oriented Programming with OCaml.
7/7/20161 Programming Languages and Compilers (CS 421) Dennis Griffith 0207 SC, UIUC Based in part on slides by Mattox.
Lesson 5 Simple extensions of the typed lambda calculus
Haskell Chapter 7.
String is a synonym for the type [Char].
CSE341: Programming Languages Lecture 11 Type Inference
ML: a quasi-functional language with strong typing
CSE341: Programming Languages Lecture 4 Records, Datatypes, Case Expressions Dan Grossman Autumn 2017.
Haskell Chapter 2.
Lecture 2:Data Types, Functional Patterns, Recursion, Polymorphism
Programming Languages and Compilers (CS 421)
Instructor : Ahmed Alalawi Slides from Chung –Ta King
Programming Languages and Compilers (CS 421)
CSE341: Programming Languages Lecture 4 Records, Datatypes, Case Expressions Dan Grossman Winter 2013.
Expanded Recursive Diagrams OCAML rapid tour, day 2
CSE341: Programming Languages Lecture 4 Records, Datatypes, Case Expressions Dan Grossman Spring 2017.
Programming Languages and Compilers (CS 421)
CSE341: Programming Languages Lecture 5 More Datatypes and Pattern-Matching Dan Grossman Autumn 2017.
PROGRAMMING IN HASKELL
CSE341: Programming Languages Lecture 5 More Datatypes and Pattern-Matching Dan Grossman Spring 2016.
CSE341: Programming Languages Lecture 5 More Datatypes and Pattern-Matching Dan Grossman Winter 2013.
CSE341: Programming Languages Lecture 5 More Datatypes and Pattern-Matching Dan Grossman Spring 2013.
Objective caml Daniel Jackson MIT Lab for Computer Science 6898: Advanced Topics in Software Design March 18, 2002.
CSE341: Programming Languages Lecture 4 Records, Datatypes, Case Expressions Dan Grossman Winter 2018.
CSE341: Programming Languages Lecture 11 Type Inference
PROGRAMMING IN HASKELL
CSE341: Programming Languages Lecture 4 Records, Datatypes, Case Expressions Dan Grossman Autumn 2018.
CSE341: Programming Languages Lecture 11 Type Inference
CSE341: Programming Languages Lecture 5 More Datatypes and Pattern-Matching Dan Grossman Autumn 2018.
CSE341: Programming Languages Lecture 5 More Datatypes and Pattern-Matching Dan Grossman Spring 2017.
Types and Classes in Haskell
PROGRAMMING IN HASKELL
CSE341: Programming Languages Lecture 4 Records, Datatypes, Case Expressions Dan Grossman Spring 2016.
Programming Languages and Compilers (CS 421) #3: Closures, evaluation of function applications, order of evaluation #4: Evaluation and Application.
Madhusudan Parthasarathy (madhu) 3112 Siebel Center
Madhusudan Parthasarathy
CSE341: Programming Languages Lecture 11 Type Inference
CSE341: Programming Languages Lecture 5 More Datatypes and Pattern-Matching Doug Woos Winter 2018.
CSE341: Programming Languages Lecture 11 Type Inference
CSE341: Programming Languages Lecture 4 Records, Datatypes, Case Expressions Dan Grossman Spring 2019.
CSE341: Programming Languages Lecture 5 More Datatypes and Pattern-Matching Dan Grossman Spring 2019.
Brett Wortzman Summer 2019 Slides originally created by Dan Grossman
Brett Wortzman Summer 2019 Slides originally created by Dan Grossman
CSE341: Programming Languages Lecture 11 Type Inference
Review Functions Lists Today: Let expressions
Review Previously in: Lots of language features: functions, lists, records, tuples, variants, pattern matching Today: No new language features New idioms.
Presentation transcript:

Review Previously User-defined data types: records, variants Built-in type constructors: list, option, * (i.e., the tuple type constructor) A type used in the List module: association lists Today: Type synonyms More about variants Exceptions

Variants vs. records vs. tuples Define Build Access Variant type Constructor name Pattern matching Record Record expression with {…} OR field selection with dot operator . Tuple N/A Tuple expression with (…) OR fst or snd Variants: one-of types aka sum types Records, tuples: each-of types aka product types

Question Which of the following would be better represented with records rather than variants? Coins, which can be pennies, nickels, dimes, or quarters Students, who have names and id numbers A dessert, which has a sauce, a creamy component, and a crunchy component A and C B and C

Question Which of the following would be better represented with records rather than variants? Coins, which can be pennies, nickels, dimes, or quarters Students, who have names and num_credits A dessert, which has a sauce, a creamy component, and a crunchy component A and C B and C

Type synonyms

Type synonyms Syntax: type id = t Anywhere you write t, you can also write id The two names are synonymous e.g. type point = float * float type vector = float list type matrix = float list list

Type synonyms type point = float*float let getx : point -> float = fun (x,_) -> x let pt : point = (1.,2.) let floatpair : float*float = (1.,3.) let one = getx pt let one' = getx floatpair

Variants

Recall: Variants type day = Sun | Mon | Tue | Wed | Thu | Fri | Sat type ptype = TNormal | TFire | TWater type peff = ENormal | ENotVery | Esuper So far, just enumerated sets of values But they can do much more...

Variants that carry data type shape = | Point of point | Circle of point * float (* center and radius *) | Rect of point * point (* lower-left and upper-right corners *) (1.0,2.0,3.0) (* Nope *) (1.0,(2.0,3.0)) (* Nope *) Circle ((1.0,2.0),3.0) (* Yep *)

Variants that carry data type shape = | Point of point | Circle of point * float (* center and radius *) | Rect of point * point (* lower-left and upper-right corners *) let area = function | Point _ -> 0.0 | Circle (_,r) -> pi *. (r ** 2.0) | Rect ((x1,y1),(x2,y2)) -> let w = x2 -. x1 in let h = y2 -. y1 in w *. h

Variants that carry data type shape = | Point of point | Circle of point * float | Rect of point * point let center = function | Point p -> p | Circle (p,_) -> p | Rect ((x1,y1),(x2,y2)) -> ((x2 -. x1) /. 2.0, (y2 -. y1) /. 2.0)

Variants that carry data type shape = | Point of point | Circle of point * float | Rect of point * point Every value of type shape is made from exactly one of the constructors and contains: a tag for which constructor it is from the data carried by that constructor Called an algebraic data type because it contains product and sum types, aka tagged union

Tagged union Union because the set of all values of the type is the union of the set of all values of the individual constructors type t = String of string | Int of int Tagged because possible to determine which underlying set a value came from type t = Left of int | Right of int "All for one and one for all": all values of variant, regardless of constructor, have same type any one value of variant built with exactly one constructor, all of which are specified in type definition

Variant types Type definition syntax: type t = C1 [of t1] | ... | Cn [of tn] A constructor that carries data is non-constant A constructor without data is constant Semantics are straightforward;

Question Given our shape variant, which function would determine whether a shape is a circle centered at the origin? type shape = | Point of point | Circle of point * float | Rect of point * point Possible answers on next slide...

A B E C D let cato = function let cato = function | Point -> false type shape = Point of point | Circle of point * float | Rect of point * point A B let cato = function | Point -> false | Circle -> true | Rect -> false let cato = function | Point _ | Rect _ -> false | Circle (0.,0.), r -> true E let cato c = c = Circle ((0.,0.),_) A: omits patterns for the carried data B: parses as (Circle 0.,0.), r C: omits pattern for radius E: can't use wildcard inside expression, only inside pattern let cato = function | Point p -> false | Circle (0.,0.) -> true | Rect (ll,ur) -> false let cato = function | Circle ((0.,0.), _) -> true | _ -> false C D

A B E C D let cato = function let cato = function | Point -> false type shape = Point of point | Circle of point * float | Rect of point * point A B let cato = function | Point -> false | Circle -> true | Rect -> false let cato = function | Point _ | Rect _ -> false | Circle (0.,0.), r -> true E let cato c = c = Circle ((0.,0.),_) A: omits patterns for the carried data B: parses as (Circle 0.,0.), r C: omits pattern for radius E: can't use wildcard inside expression, only inside pattern let cato = function | Point p -> false | Circle (0.,0.) -> true | Rect (ll,ur) -> false let cato = function | Circle ((0.,0.), _) -> true | _ -> false C D

Recursive variants

Try Me. type dumb = | Nothing | I of int | I of int * dumb

Implement lists with variants type intlist = Nil | Cons of int * intlist let emp = Nil let l3 = Cons (3, Nil) (* 3::[] or [3]*) let l123 = Cons(1, Cons(2, l3)) (* [1;2;3] *) let rec sum (l:intlist) = match l with | Nil -> 0 | Cons(h,t) -> h + sum t

Implement lists with variants let rec length = function | Nil -> 0 | Cons (_,t) -> 1 + length t (* length : intlist -> int *) let empty = function | Nil -> true | Cons _ -> false (* empty: intlist -> bool *)

Parameterized variants

Lists of any type Have: lists of ints Want: lists of ints, lists of strings, lists of pairs, lists of records that themselves contain lists of pairs, ... Non-solution: copy code type stringlist = SNil | SCons of string * stringlist let empty = function | SNil -> true | SCons _ -> false

Lists of any type Solution: parameterize types on other types type 'a mylist = Nil | Cons of 'a * 'a mylist let l3 = Cons (3, Nil) (* [3] *) let lhi = Cons ("hi", Nil) (* ["hi"] *)

Lists of any type type 'a mylist = | Nil | Cons of 'a * 'a mylist mylist is not a type but a type constructor: takes a type as input and returns a type int mylist string mylist (int*string) mylist ...

Functions on parameterized variants let rec length = function | Nil -> 0 | Cons (_,t) -> 1 + length t (* length : 'a mylist -> int *) let empty = function | Nil -> true | Cons _ -> false (* empty: 'a mylist -> bool *) code stays the same; only the types change

Parametric polymorphism poly = many, morph = form write function that works for many arguments regardless of their type closely related to Java generics, related to C++ template instantiation, ...

The power of variants

Lists are just variants OCaml effectively codes up lists as variants: type 'a list = [] | :: of 'a * 'a list list is a type constructor parameterized on type variable 'a [] and :: are constructors Just a bit of syntactic magic in the compiler to use [] and :: instead of alphabetic identifiers

We should stop here. Define a binary tree of ints. Define a binary tree of anytype. Define a binary tree of strings and ints ;-)

Options are just variants OCaml effectively codes up options as variants: type 'a option = None | Some of 'a option is a type constructor parameterized on type variable 'a None and Some are constructors

Exceptions are (mostly) just variants OCaml effectively codes up exceptions as slightly strange variants: type exn exception MyNewException of string Type exn is an extensible variant that may have new constructors added after its original definition Raise exceptions with raise e, where e is a value of type exn Handle exceptions with pattern matching, just like you would process any variant