Datatype declarations

Similar documents
Exercises on ML. Programming Languages. Chanseok Oh

Chapter 3 Linear Structures: Lists

Chapter 3 Linear Structures: Lists

A First Look at ML. Chapter Five Modern Programming Languages, 2nd ed. 1

CSC/MAT-220: Lab 6. Due: 11/26/2018

CSE 341 Section 5. Winter 2018

Flang typechecker Due: February 27, 2015

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

The type checker will complain that the two branches have different types, one is string and the other is int

Handout 2 August 25, 2008

CSCI-GA Final Exam

Lists. Michael P. Fourman. February 2, 2010

Processadors de Llenguatge II. Functional Paradigm. Pratt A.7 Robert Harper s SML tutorial (Sec II)

CSCI-GA Scripting Languages

CMSC 330: Organization of Programming Languages. Functional Programming with Lists

A quick introduction to SML

CSE341: Programming Languages Lecture 9 Function-Closure Idioms. Dan Grossman Winter 2013

Standard ML. Data types. ML Datatypes.1

SML A F unctional Functional Language Language Lecture 19

Begin at the beginning

Overloading, Type Classes, and Algebraic Datatypes

A Third Look At ML. Chapter Nine Modern Programming Languages, 2nd ed. 1

OCaml. ML Flow. Complex types: Lists. Complex types: Lists. The PL for the discerning hacker. All elements must have same type.

CMSC 330: Organization of Programming Languages. Functional Programming with Lists

CS 457/557: Functional Languages

CMSC 330: Organization of Programming Languages. OCaml Imperative Programming

CMSC 330: Organization of Programming Languages. OCaml Imperative Programming

1. true / false By a compiler we mean a program that translates to code that will run natively on some machine.

All the operations used in the expression are over integers. a takes a pair as argument. (a pair is also a tuple, or more specifically, a 2-tuple)

Introduction to OCaml

CSC324- TUTORIAL 5. Shems Saleh* *Some slides inspired by/based on Afsaneh Fazly s slides

CSE341, Fall 2011, Midterm Examination October 31, 2011

Recap from last time. Programming Languages. CSE 130 : Fall Lecture 3: Data Types. Put it together: a filter function

SMURF Language Reference Manual Serial MUsic Represented as Functions

CSE341: Programming Languages Lecture 7 First-Class Functions. Dan Grossman Winter 2013

CSCC24 Functional Programming Typing, Scope, Exceptions ML

Introduction to OCaml

Haskell 5.1 INTERACTIVE SESSIONS AND THE RUN-TIME SYSTEM

CSE 341 : Programming Languages Midterm, Spring 2015

Learning Standard ML

Scheme. Functional Programming. Lambda Calculus. CSC 4101: Programming Languages 1. Textbook, Sections , 13.7

A Brief Introduction to Standard ML

CSE413: Programming Languages and Implementation Racket structs Implementing languages with interpreters Implementing closures

CS 314 Principles of Programming Languages

COMP 105 Homework: Type Systems

COMP 105 Assignment: Hindley-Milner Type Inference

Standard ML. Curried Functions. ML Curried Functions.1

Programming Languages and Compilers (CS 421)

CS 11 Ocaml track: lecture 2

CS 11 Haskell track: lecture 1

Tail Recursion: Factorial. Begin at the beginning. How does it execute? Tail recursion. Tail recursive factorial. Tail recursive factorial

Implementing nml: Hindley-Milner Type Inference

CSE341: Programming Languages Lecture 9 Function-Closure Idioms. Dan Grossman Fall 2011

Haske k ll An introduction to Functional functional programming using Haskell Purely Lazy Example: QuickSort in Java Example: QuickSort in Haskell

Lists. Adrian Groza. Department of Computer Science Technical University of Cluj-Napoca

SCHEME 7. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. October 29, 2015

News. Programming Languages. Complex types: Lists. Recap: ML s Holy Trinity. CSE 130: Spring 2012

An introduction introduction to functional functional programming programming using usin Haskell

Racket. CSE341: Programming Languages Lecture 14 Introduction to Racket. Getting started. Racket vs. Scheme. Example.

# true;; - : bool = true. # false;; - : bool = false 9/10/ // = {s (5, "hi", 3.2), c 4, a 1, b 5} 9/10/2017 4

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define

CSE341, Fall 2011, Midterm Examination October 31, 2011

CSE341 Autumn 2017, Midterm Examination October 30, 2017

A Fourth Look At ML. Chapter Eleven Modern Programming Languages, 2nd ed. 1

Booleans (aka Truth Values) Programming Languages and Compilers (CS 421) Booleans and Short-Circuit Evaluation. Tuples as Values.

RSL Reference Manual

CSE341: Programming Languages Lecture 4 Records, Datatypes, Case Expressions. Dan Grossman Spring 2013

CS Lecture 5: Pattern Matching. Prof. Clarkson Fall Today s music: Puff, the Magic Dragon by Peter, Paul & Mary

L3 Programming September 19, OCaml Cheatsheet

(Refer Slide Time: 4:00)

Side note: Tail Recursion. Begin at the beginning. Side note: Tail Recursion. Base Types. Base Type: int. Base Type: int

CSE 341: Programming Languages

How does ML deal with +?

Lecture #13: Type Inference and Unification. Typing In the Language ML. Type Inference. Doing Type Inference

ML Built-in Functions

Lecture 2: The Basis of SML

Advanced Programming Handout 7. Monads and Friends (SOE Chapter 18)

15 150: Principles of Functional Programming. More about Higher-Order Functions

Programming Paradigms Languages F28PL, Lecture 1

n n Try tutorial on front page to get started! n spring13/ n Stack Overflow!

Fall 2017 Discussion 7: October 25, 2017 Solutions. 1 Introduction. 2 Primitives

Programming Language Concepts, cs2104 Lecture 04 ( )

CSE 130: Programming Languages. Polymorphism. Ranjit Jhala UC San Diego

Programming Paradigms

Specification and Verification in Higher Order Logic

COMP 105 Assignment: Core ML

Haskell Overview II (2A) Young Won Lim 8/9/16

PROGRAMMING IN HASKELL. Chapter 2 - First Steps

Introduction to Functional Programming in OCaml

Haskell Introduction Lists Other Structures Data Structures. Haskell Introduction. Mark Snyder

This example highlights the difference between imperative and functional programming. The imperative programming solution is based on an accumulator

Homework 3 COSE212, Fall 2018

CSCE 314 TAMU Fall CSCE 314: Programming Languages Dr. Flemming Andersen. Haskell Functions

The PCAT Programming Language Reference Manual

On Academic Dishonesty. Declarative Computation Model. Single assignment store. Single assignment store (2) Single assignment store (3)

Module 8: Local and functional abstraction

Shell CSCE 314 TAMU. Haskell Functions

Introduction to SML Basic Types, Tuples, Lists, Trees and Higher-Order Functions

Programming in Standard ML: Continued

Introduction to Haskell

Transcription:

Datatype declarations datatype suit = HEARTS DIAMONDS CLUBS SPADES datatype a list = nil (* copy me NOT! *) op :: of a * a list datatype a heap = EHEAP HEAP of a * a heap * a heap type suit val HEARTS : suit,... type a list val nil : forall a. a list val op :: : forall a. a * a list -> a list type a heap val EHEAP: forall a. a heap val HEAP : forall a. a * a heap * a heap -> a heap

Eliminate values of algebraic types New language constructcase (an expression) fun length xs = case xs of [] => 0 (x::xs) => 1 + length xs Clausal definition is preferred (sugar forval rec,fn,case)

case works for any datatype fun tostr t = case t of EHEAP => "empty heap" HEAP (v, left, right) => "nonempty heap" But often a clausal definition is better style: fun tostr EHEAP = "empty heap" tostr (HEAP (v,left,right)) = "nonempty heap"

Types and their ML constructs Type Produce Consume Introduce Eliminate arrow Lambda (fn) Application algebraic Apply constructor Pattern match tuple (e1,..., en) Pattern match!

Type-directed coding Common idea in functional programming: lifting val lift : forall a. ( a -> bool) -> ( a list -> bool) What (sensible) functions have this type?

Working...

Type-directed coding (results) val lift : ( a -> bool) -> ( a list -> bool) fun lift p = (fn xs => (case xs of [] => false z::zs => p z orelse lift p zs))

Merge top-levelfn intofun fun lift p xs = case xs of [] => false z::zs => p z orelse lift p zs

Merge top-levelcase intofun fun lift p [] = false lift p (z::zs) = p z orelse lift p zs

I know this function! fun exists p [] = false exists p (z::zs) = p z orelse exists p zs

Frequently overlooked An algebraic data type is a collection of alternatives Don t forget: Each alternative must have a name The thing named is the value constructor (Also called datatype constructor )

Define algebraic data types for SX 1 and SX 2, where SX 1 ATOM LIST SX 1 µ SX 2 ATOM (cons v 1 v 2 ) v 1 ¾ SX 2 v 2 ¾ SX 2 (take ATOM, with ML typeatom as given)

Wait for it...

Exercise answers datatype sx1 = ATOM1 of atom LIST1 of sx1 list datatype sx2 = ATOM2 of atom PAIR2 of sx2 * sx2

Exception handling in action loop (evaldef (reader (), rho, echo)) handle EOF => finish () Div => continue "Division by zero" Overflow => continue "Arith overflow" RuntimeError msg => continue ("error: " ˆ msg) IO.Io {name,...} => continue ("I/O error: " ˆ name) SyntaxError msg => continue ("error: " ˆ msg) NotFound n => continue (n ˆ "not found")

ML Traps and pitfalls

Order of clauses matters fun take n (x::xs) = x :: take (n-1) xs take 0 xs = [] take n [] = [] (* what goes wrong? *)

Gotcha overloading - fun plus x y = x + y; > val plus = fn : int -> int -> int - fun plus x y = x + y : real; > val plus = fn : real -> real -> real

Gotcha equality types - (fn (x, y) => x = y); > val it = fn : a. a * a -> bool Tyvar a is equality type variable : values must admit equality (functions don t admit equality)

Gotcha parentheses Put parentheses around anything with case,handle,fn Function application has higher precedence than any infix operator

Syntactic sugar for lists - 1 :: 2 :: 3 :: 4 :: nil; (* :: associates to the right *) > val it = [1, 2, 3, 4] : int list - "the" :: "ML" :: "follies" :: []; > val it = ["the", "ML", "follies"] : string list > concat it; val it = "themlfollies" : string

ML from 10,000 feet

The value environment Names bound to immutable values Immutableref andarray values point to mutable locations ML has no binding-changing assignment Definitions add new bindings (hide old ones): val pattern=exp val rec pattern = exp fun ident patterns = exp datatype... =...

At top level, definitions Nesting environments Definitions contain expressions: def ::=val pattern=exp Expressions contain definitions: exp ::=let defs in exp end Sequence of defs has let-star semantics

What is a pattern? pattern ::= variable wildcard value-constructor [pattern] tuple-pattern record-pattern integer-literal list-pattern Design bug: no lexical distinction between VALUE CONSTRUCTORS variables Workaround: programming convention

Function pecularities: 1 argument Each function takes 1 argument, returns 1 result For multiple arguments, use tuples! fun factorial n = let fun f (i, prod) = if i > n then prod else f (i+1, i*prod) in f (1, 1) end fun factorial n = (* you can also Curry *) let fun f i prod = if i > n then prod else f (i+1) (i*prod) in f 1 1 end

Mutual recursion Let-star semantics will not do. Useand (different fromandalso)! fun a x = b (x-1) and b y = a (y-1)

Syntax of ML types Abstract syntax for types: ty µ TYVAR of string TYCON of string * ty list type variable apply type constructor Each tycon takes fixed number of arguments. nullary int,bool,string,... unary list,option,... binary -> n-ary tuples (infix*)

Syntax of ML types Concrete syntax is baroque: ty µ tyvar tycon ty tycon (ty,, ty) tycon ty* *ty ty-> ty (ty) tyvar µ identifier type variable (nullary) type constructor (unary) type constructor (n-ary) type constructor tuple type arrow (function) type a, b, c, tycon µ identifier list,int,bool,

Polymorphic types Abstract syntax of type scheme : µ FORALL of tyvar list * ty Bad decision: left out of concrete syntax (fn (f,g) => fn x => f (g x)) : a, b, c. ( a -> b) * ( c -> a) -> ( c -> b) Key idea: subtitute for quantified type variables

Old and new friends op o : a, b, c. ( a -> b) * ( c -> a) -> c -> b length : a. a list -> int map : a, b. ( a -> b) -> ( a list -> b list) curry : a, b, c. ( a * b -> c) -> a -> b -> c id : a. a -> a