EPITA - Practical Programming 06 - Advanced Module Usage

Size: px
Start display at page:

Download "EPITA - Practical Programming 06 - Advanced Module Usage"

Transcription

1 More EPITA - Practical Programming 06 - Advanced Module Usage marwan.burelle@lse.epita.fr

2 Outline More 1 Embedded Declaring Module Types 2 Data Structures And Code Safety Opaque Types More Advanced Stuff 3 Playing Around Signature

3 More Embedded Declaring Module Types

4 Module Sublanguage More Embedded Declaring Module Types are not only usable at file level OCaml provides a sublanguage dedicated to modules One is able to build embedded modules, describe module interfaces or construct function over modules.

5 Overview More 1 Embedded Declaring Module Types Embedded Declaring Module Types

6 Building Local Module Embedded module Vector = struct type a t = { capacity : int; mutable size : int; tab : a array; } let make sz = { capacity = sz; size = 0; tab = Array.make sz (Obj.magic None) } let add v x = if v.size < v.capacity then begin v.tab.(v.size) <- x; v.size <- v.size + 1; end end More Embedded Declaring Module Types let v = Vector.make 10

7 Accessing Embedded (* module: a.ml *) module B = struct type t = int let compare a b = a - b end a.ml c.ml (* module: c.ml *) type t = A.B.t list let empty : t = [] let rec insert x = function (h::_) as l when A.B.compare x h = 0 -> l h::t when A.B.compare x h > 0 -> h :: insert x t l -> x :: l More Embedded Declaring Module Types

8 Overview More 1 Embedded Declaring Module Types Embedded Declaring Module Types

9 Embedded Module And Interface Minimal Set module type MinSetType = sig type a t (* Create an empty set *) val create : unit -> a t (* Test for emptyness *) val is_empty : a t -> bool (* Add an element *) val add : a t -> a -> unit (* Extract min value *) val take_min : a t -> a end Minimal Set module DummSet: MinSetType = struct type a t = { mutable l : a list; } let create () = {l = []} let is_empty s = s.l = [] let add s x = s.l<-x::s.l let take_min s = match List.sort compare s.l with [] -> raise Not_found h::t -> s.l <- t; h end More Embedded Declaring Module Types

10 Direct Interface Assignment More Typed Module module A : sig type t val compare : t -> t -> int end = struct type t = int let compare a b = Pervasives.compare a b end Embedded Declaring Module Types

11 Affecting Types To Existing More Forcing Types module OrderedStr : sig type t val compare : t -> t -> int end = String Embedded Declaring Module Types The existing module must provide declared symbols The new module will only provide declared symbols

12 More Data Structures And Code Safety Opaque Types More Advanced Stuff

13 Overview More 2 Data Structures And Code Safety Opaque Types More Advanced Stuff Data Structures And Code Safety Opaque Types More Advanced Stuff

14 Quick n Dirty Ordered Set Module set.ml type a t = a list let empty = [] let is_empty s = s = [] let rec add s = function (h::_) as l when h = s -> l h::t when h < s -> h :: add s t l -> s::l let rec mem x = function [] -> false h::t when h <= x -> x=h mem x t _ -> false let rec union s1 s2 = match (s1,s2) with ([],s) (s,[]) -> s (h1::t1, h2::_) when h1 < h2 -> h1 :: union t1 s2 (h1::_, h2::t2) when h1 > h2 -> h2 :: union s1 t2 (h1::t1, _::t2) -> h1 :: union t1 t2 More Data Structures And Code Safety Opaque Types More Advanced Stuff

15 Is This Module Safe? More An ordered set must verify two properties: It must be sorted It must not contain twice the same element Take a look at function add x s: if s is a correct set then: x will be added, to its right place, only if it is not in s In any case, the output set will be correct. Data Structures And Code Safety Opaque Types More Advanced Stuff If the input set is not correct, we can t guaranteed the correctness of the output. union has the same properties, and, of course, mem can only provide a correct answer if its input is a correct set.

16 Unsafe scenario More Unsafe use of set let myset = [1;2;4;3] let myset2 = add 3 myset Evaluation output val myset2 : int list = [1; 2; 3; 4; 3] Data Structures And Code Safety Opaque Types More Advanced Stuff The result is not a correct set, as expected.

17 Solutions? More Verifies properties when entering set operations: too expensive Manually check all usage of set operations: unrealistic and unsafe Enforce that only values built using Set operations are used: Probably the good solutions... Data Structures And Code Safety Opaque Types More Advanced Stuff

18 Overview More 2 Data Structures And Code Safety Opaque Types More Advanced Stuff Data Structures And Code Safety Opaque Types More Advanced Stuff

19 Hiding More If we re able to hide the fact that sets are lists, we won t be able to provide ill-formed values to set operations. That s the purpose of opaque types! set.mli type a t (* no implem *) Data Structures And Code Safety Opaque Types More Advanced Stuff val empty : a t val is_empty : a t -> bool val add : a -> a t -> a t val mem : a -> a t -> bool val union : a t -> a t -> a t

20 Hiding wrong.ml let main () = let l = [1;2;4;3] in let l2 = Set.add 3 l in () (* Nothing to do *) let _ = main () File "wrong.ml", line 3, characters 21-22: Error: This expression has type int list but an expression was expected of type int Set.t More Data Structures And Code Safety Opaque Types More Advanced Stuff We finaly get what we want, only value constructed by the module operations are usable!

21 More On Opaque Types More Enforce loose coopling: we can completely rewrite the module implementation without rewriting the code using it. With a good naming convention, data usage are more clear and self-explaining. Of course, nothing is perfect: We can t extend the module easily The module must provide all the possible operations requiring access to the inner representation. Data Structures And Code Safety Opaque Types More Advanced Stuff

22 Multi-Level Opacity mixed.ml module T = struct type a t = a list let empty = [] let is_empty s = s = [] let rec add s = function (h::_) as l when h = s -> l h::t when h < s -> h :: add s t l -> s::l end let set_factory n = let rec aux a = function 0 -> a n -> aux (n::a) (n-1) in aux [] n More Data Structures And Code Safety Opaque Types More Advanced Stuff mixed.mli module T : sig type a t val empty : a list val is_empty : a list -> bool val add : a -> a list -> a list end val set_factory : int -> int T.t

23 Overview More 2 Data Structures And Code Safety Opaque Types More Advanced Stuff Data Structures And Code Safety Opaque Types More Advanced Stuff

24 Phantom Types: Ref Types More Ref module Ref : sig type t val create : int -> t val set : t -> int -> unit val get : t -> int end = struct type t = int ref let create x = ref x let set t x = t := x let get t =!t end Data Structures And Code Safety Opaque Types More Advanced Stuff

25 Phantom Types: Building Read-Only Ref RO-Ref type readonly type readwrite module PRef : sig type a t val create : int -> readwrite t val set : readwrite t -> int -> unit val get : a t -> int val readonly : a t -> readonly t end = struct type a t = Ref.t let create = Ref.create let set = Ref.set let get = Ref.get let readonly x = x end More Data Structures And Code Safety Opaque Types More Advanced Stuff

26 Phantom Types More Trying let sumrefs reflist = List.fold_left (+) 0 (List.map PRef.get reflist) let increfs reflist = List.iter (fun r -> PRef.set r (PRef.get r + 1)) reflist Data Structures And Code Safety Opaque Types More Advanced Stuff Typing val sumrefs : a PRef.t list -> int val increfs : readwrite PRef.t list -> unit

27 More Playing Around Signature

28 Overview More 3 Playing Around Signature Playing Around Signature

29 Set With Parametric Order More Using default ordering is not always convenient, and even somtimes not possible (like objects.) The usual solution is to provide a comparison function. set.ml type a t = a list let empty = [] let is_empty s = s = [] let rec add cmp s = function (h::_) as l when cmp h s = 0 -> l h::t when cmp h s < 0 -> h :: add cmp s t l -> s::l let rec mem cmp x = function [] -> false h::t when cmp h x <= 0 -> cmp x h = 0 mem cmp x t _ -> false Playing Around Signature

30 Using Higher Order Parameter More The issue with the previous solution is that we need to pass the comparison function to all operations. Even if we use an opaque type, we may break the data structure by providing different comparison functions. Playing Around Signature fail! let s = Set.add (fun a b -> a - b) 1 ( Set.add (fun a b -> b - a) 2 Set.empty )

31 Overview More 3 Playing Around Signature Playing Around Signature

32 Poor Man Polymorphism More trickyset.ml module T = (* Put your module here *) type t = T.t list let empty = [] let is_empty s = s = [] let rec add s = function (h::_) as l when T.compare h s = 0 -> l h::t when T.compare h s < 0 -> h :: add s t l -> s::l let rec mem x = function [] -> false h::t when T.compare h x <= 0 -> T.compare x h = 0 mem x t _ -> false Playing Around Signature

33 Module As Parameter? More In the previous example, we build our module based on the existence of a module T providing what we need. The issue is that we need to copy and modify this module to build another version. What if T was a parameter to a function from module to module? Playing Around Signature This is the idea of functor: a function from modules to module

34 Building A Functor More We need to fix the type of the parameter. We ll define a module signature for that and then define the functor: set.ml (* Module Type of the parameter *) module type OrderedType = sig type t val compare: t -> t -> int end (* Defining The Functor *) module Make (T:OrderedType) = struct type t = T.t list (*... *) end Playing Around Signature

35 Functor s Code set.ml module Make (T:OrderedType) = struct type t = T.t list let empty = [] let is_empty s = s = [] let rec add s = function (h::_) as l when T.compare h s = 0 -> l h::t when T.compare h s < 0 -> h :: add s t l -> s::l let rec mem x = function [] -> false h::t when T.compare h x <= 0 -> T.compare x h = 0 mem x t _ -> false end More Playing Around Signature

36 Using Our Functor More Set of int module Int = struct type t = int let compare a b = Pervasives.compare a b end Playing Around Signature module IntSet = Set.Make(Int)

37 Functor Instantiation Is A Module More Type of our functor module IntSet : sig type t = Int.t list val empty : a list val is_empty : a list -> bool val add : Int.t -> Int.t list -> Int.t list val mem : Int.t -> Int.t list -> bool end Playing Around Signature

38 Overview More 3 Playing Around Signature Playing Around Signature

39 Functor s Signature More Using.mli file set.mli module type OrderedType = sig type t val compare : t -> t -> int end Playing Around Signature module Make : functor (T : OrderedType) -> sig type t = T.t list val empty : t val is_empty : t -> bool val add : T.t -> t -> t val mem : T.t -> t -> bool end

40 And Opaque Types More You can rewrite the signature with an opaque version for the type t This form will prevent usage of ill-formed set. It also protect us from mixing containers built on the same type but with different comparison functions. Playing Around Signature

41 Set Of String strset.ml module Str = struct type t = string let compare a b = compare (String.lowercase a) (String.lowercase b) end module NoCaseStrSet = Set.Make(Str) module CaseStrSet = Set.Make(String) More Playing Around Signature let s = NoCaseStrSet.add "Aa" ( CaseStrSet.add "AA" ( CaseStrSet.add "aa" CaseStrSet.empty ) )

42 Functor s Signature More Using module signature set.ml module type S = sig type content type t val empty : t val is_empty : t -> bool val add : content -> t -> t val mem : content -> t -> bool end module Make (T:OrderedType) = struct type content = T.t type t = content list (*... *) end Playing Around Signature

43 Functor s Signature More Using module signature set.mli module type S = sig type content type t val empty : t val is_empty : t -> bool val add : content -> t -> t val mem : content -> t -> bool end module Make (T : OrderedType) : S Playing Around Signature

44 Functor s Signature More The previous solution as a major drawback... Too bad module StrSet = Set.Make(String) Playing Around Signature let s = StrSet.add "aa" StrSet.empty Error: This expression has type string but an expression was expected of type StrSet.content = Set.Make(String).content

45 Functor s Signature More Using module signature (this one is working... ) set.mli module type S = sig type content type t val empty : t val is_empty : t -> bool val add : content -> t -> t val mem : content -> t -> bool end module Make (T : OrderedType) : S with type content = T.t Playing Around Signature

CMSC 330: Organization of Programming Languages. Basic OCaml Modules

CMSC 330: Organization of Programming Languages. Basic OCaml Modules CMSC 330: Organization of Programming Languages Basic OCaml Modules 1 Modules So far, most everything we ve defined has been at the top-level of OCaml This is not good software engineering practice A better

More information

CS3110 Spring 2016 Lecture 6: Modules

CS3110 Spring 2016 Lecture 6: Modules CS3110 Spring 2016 Lecture 6: Modules Modules are the O part of OCaml, influenced by objects in Java. We see the evolution: Classic ML, CambridgeML (CAML), and finally OCaml. David McQueen is writing the

More information

Principles of Functional Programming

Principles of Functional Programming 15-150 Principles of Functional Programming Some Slides for Lecture 16 Modules March 20, 2018 Michael Erdmann Signatures & Structures A signature specifies an interface. A structure provides an implementation.

More information

Lecture 7: The Untyped Lambda Calculus

Lecture 7: The Untyped Lambda Calculus Lecture 7: The Untyped Lambda Calculus Writing the interpreter Polyvios Pratikakis Computer Science Department, University of Crete Type Systems and Static Analysis Pratikakis (CSD) Untyped λ-calculus

More information

OCaml Data CMSC 330: Organization of Programming Languages. User Defined Types. Variation: Shapes in Java

OCaml Data CMSC 330: Organization of Programming Languages. User Defined Types. Variation: Shapes in Java OCaml Data : Organization of Programming Languages OCaml 4 Data Types & Modules So far, we ve seen the following kinds of data Basic types (int, float, char, string) Lists Ø One kind of data structure

More information

CMSC 430 Introduction to Compilers. Fall Everything (else) you always wanted to know about OCaml (but were afraid to ask)

CMSC 430 Introduction to Compilers. Fall Everything (else) you always wanted to know about OCaml (but were afraid to ask) CMSC 430 Introduction to Compilers Fall 2015 Everything (else) you always wanted to know about OCaml (but were afraid to ask) OCaml You know it well from CMSC 330 All programming projects will be in OCaml

More information

Type structure is a syntactic discipline for maintaining levels of abstraction John Reynolds, Types, Abstraction and Parametric Polymorphism

Type structure is a syntactic discipline for maintaining levels of abstraction John Reynolds, Types, Abstraction and Parametric Polymorphism Chapter 6 Abstraction Type structure is a syntactic discipline for maintaining levels of abstraction John Reynolds, Types, Abstraction and Parametric Polymorphism Abstraction, also known as information

More information

CMSC 330, Fall 2013, Practice Problems 3

CMSC 330, Fall 2013, Practice Problems 3 CMSC 330, Fall 2013, Practice Problems 3 1. OCaml and Functional Programming a. Define functional programming b. Define imperative programming c. Define higher-order functions d. Describe the relationship

More information

L28: Advanced functional programming

L28: Advanced functional programming L28: Advanced functional programming Exercise 2 Due on 8th March 2017 Submission instructions Your solutions for this exericse should be handed in to the Graduate Education Office by 4pm on the due date.

More information

Abstraction. Leo White. February Jane Street 1/ 88

Abstraction. Leo White. February Jane Street 1/ 88 1/ 88 Abstraction Leo White Jane Street February 2017 2/ 88 Abstraction When faced with creating and maintaining a complex system, the interactions of different components can be simplified by hiding the

More information

A Short Introduction to OCaml

A Short Introduction to OCaml École Polytechnique INF549 A Short Introduction to OCaml Jean-Christophe Filliâtre September 11, 2018 Jean-Christophe Filliâtre A Short Introduction to OCaml INF549 1 / 102 overview lecture labs Jean-Christophe

More information

Reference Cells. Example

Reference Cells. Example Introduction to Objective Caml Part 2 Stefan Wehr University of Freiburg. November 8, 2006 Remember: Variables are only names for values Can t asn to variables Solution: reference cells Constructor: ref

More information

Lists. Michael P. Fourman. February 2, 2010

Lists. Michael P. Fourman. February 2, 2010 Lists Michael P. Fourman February 2, 2010 1 Introduction The list is a fundamental datatype in most functional languages. ML is no exception; list is a built-in ML type constructor. However, to introduce

More information

Abstraction Functions and Representation Invariants

Abstraction Functions and Representation Invariants Abstraction Functions and Representation Invariants Prof. Clarkson Fall 2017 Today s music: In C by Terry Riley A2 Implement a text adventure game engine, and write your own adventure Experience with lists,

More information

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques (CIS120) Lecture 10 February 5 th, 2016 Abstract types: sets Lecture notes: Chapter 10 What is the value of this expresssion? let f (x:bool) (y:int) : int = if x then

More information

Parametricity. Leo White. February Jane Street 1/ 70

Parametricity. Leo White. February Jane Street 1/ 70 1/ 70 Parametricity Leo White Jane Street February 2017 2/ 70 Parametricity Polymorphism allows a single piece of code to be instantiated with multiple types. Polymorphism is parametric when all of the

More information

CMSC 330: Organization of Programming Languages. Objects and Abstract Data Types

CMSC 330: Organization of Programming Languages. Objects and Abstract Data Types CMSC 330: Organization of Programming Languages Objects and Abstract Data Types Abstract Data Types Expose signature operators to create, combine, and observe values Hide representation & implementations

More information

Modules and Representation Invariants

Modules and Representation Invariants Modules and Representation Invariants COS 326 Andrew W. Appel Princeton University slides copyright 2013-2015 David Walker and Andrew W. Appel In previous classes: Reasoning about individual OCaml expressions.

More information

Last time: generic programming

Last time: generic programming 1/ 55 Last time: generic programming val (=) : { D: DATA } D. t D. t bool 2/ 55 This time: monads etc., continued >>= effect E 3/ 55 Recap: monads, bind and let An imperative program let id =! counter

More information

School of Computer Science

School of Computer Science A27217 No calculator permitted in this examination School of Computer Science First Year - BSc Artificial Intelligence and Computer Science First Year - BSc Natural Sciences First Year - BSc Computer Science

More information

Some Advanced ML Features

Some Advanced ML Features Some Advanced ML Features Mooly Sagiv Michael Clarkson, Cornell CS 3110 Data Structures and Functional Programming University of Washington: Dan Grossman ML is small Small number of powerful constructs

More information

Signature review: collect declarations

Signature review: collect declarations Signature review: collect declarations signature QUEUE = sig type a queue (* another abstract type *) exception Empty val empty : a queue val put : a * a queue -> a queue val get : a queue -> a * a queue

More information

Modules and Abstract Data Types

Modules and Abstract Data Types Modules and Abstract Data Types COS 326 Andrew W. Appel Princeton University slides copyright 2013-2015 David Walker and Andrew W. Appel The Reality of Development We rarely know the right algorithms or

More information

Lecture 31: Graph Search & Game 10:00 AM, Nov 16, 2018

Lecture 31: Graph Search & Game 10:00 AM, Nov 16, 2018 CS Integrated Introduction to Computer Science Klein Lecture : Graph Search & Game 0:00 AM, Nov, 08 Contents Rooted-tree search DAG search Search in a graph with cycles 4 The GAME Signature Functors Rooted-tree

More information

1 Splay trees. 2 Implementation of splay. CS134b Homework #1 January 8, 2001 Due January 15, 2001

1 Splay trees. 2 Implementation of splay. CS134b Homework #1 January 8, 2001 Due January 15, 2001 CSb Homework # January, 00 Due January, 00 Splay trees One of the most important data structures used in compilers are sets and tables of arbitrary elements. For example, when we do type checking, we will

More information

CSE 130, Fall 2005: Final Examination

CSE 130, Fall 2005: Final Examination CSE 130, Fall 2005: Final Examination Name: ID: Instructions, etc. 1. Write your answers in the space provided. 2. Wherever it says explain, write no more than three lines as explanation. The rest will

More information

G Programming Languages - Fall 2012

G Programming Languages - Fall 2012 G22.2110-003 Programming Languages - Fall 2012 Lecture 10 Thomas Wies New York University Review Last class ML Outline Modules Sources: PLP, 3.3.4, 3.3.5, 3.8 McConnell, Steve. Code Complete, Second Edition,

More information

CSE 130, Fall 2006: Final Examination

CSE 130, Fall 2006: Final Examination CSE 130, Fall 2006: Final Examination Name: ID: Instructions, etc. 1. Write your answers in the space provided. 2. Wherever it says explain, write no more than three lines as explanation. The rest will

More information

Modular Programming. Prof. Clarkson Fall Today s music: "Giorgio By Moroder" by Daft Punk

Modular Programming. Prof. Clarkson Fall Today s music: Giorgio By Moroder by Daft Punk Modular Programming Prof. Clarkson Fall 2017 Today s music: "Giorgio By Moroder" by Daft Punk Moog modular synthesizer Based in Trumansburg, NY, 1953-1971 Game changing! picked up by the Beatles, the Rolling

More information

Life in a Post-Functional World

Life in a Post-Functional World Life in a Post-Functional World Definitions Functional Programming Definitions Functional Programming Programming with functions! Definitions Functional Programming Programming with functions! Functions

More information

CS Lectures 2-3. Introduction to OCaml. Polyvios Pratikakis

CS Lectures 2-3. Introduction to OCaml. Polyvios Pratikakis CS 490.40 Lectures 2-3 Introduction to OCaml Polyvios Pratikakis Based on slides by Jeff Foster History ML: Meta Language 1973, University of Edinburg Used to program search tactics in LCF theorem prover

More information

Sample Exam; Solutions

Sample Exam; Solutions Sample Exam; Solutions Michael P. Fourman February 2, 2010 1 Introduction This document contains solutions to the sample questions given in Lecture Note 10 Short Question 5 marks Give the responses of

More information

CMSC 330, Fall 2013, Practice Problem 3 Solutions

CMSC 330, Fall 2013, Practice Problem 3 Solutions CMSC 330, Fall 2013, Practice Problem 3 Solutions 1. OCaml and Functional Programming a. Define functional programming Programs are expression evaluations b. Define imperative programming Programs change

More information

CSCI 2041: First Class Functions

CSCI 2041: First Class Functions CSCI 2041: First Class Functions Chris Kauffman Last Updated: Thu Oct 18 22:42:48 CDT 2018 1 Logistics Assignment 3 multimanager Reading OCaml System Manual: Ch 26: List and Array Modules, higher-order

More information

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques (CIS120) Lecture 11 February 5, 2018 Review: Abstract types Finite Maps Homework 3 due tomorrow at 11:59:59pm Announcements (Homework 4 is due Tuesday, 2/20, and won

More information

CS Lecture 14: Hash tables. Prof. Clarkson Spring Today s music: Re-hash by Gorillaz

CS Lecture 14: Hash tables. Prof. Clarkson Spring Today s music: Re-hash by Gorillaz CS 3110 Lecture 14: Hash tables Prof. Clarkson Spring 2015 Today s music: Re-hash by Gorillaz Review Recently: Data abstractions Lists, stacks, queues, dictionaries, polynomials,... Imperative features

More information

Two approaches to writing interfaces

Two approaches to writing interfaces Two approaches to writing interfaces Interface projected from implementation: No separate interface Compiler extracts from implementation (CLU, Java class, Haskell) When code changes, must extract again

More information

Pattern Matching and Abstract Data Types

Pattern Matching and Abstract Data Types Pattern Matching and Abstract Data Types Tom Murphy VII 3 Dec 2002 0-0 Outline Problem Setup Views ( Views: A Way For Pattern Matching To Cohabit With Data Abstraction, Wadler, 1986) Active Patterns (

More information

CS 11 Ocaml track: lecture 4. Today: modules

CS 11 Ocaml track: lecture 4. Today: modules CS 11 Ocaml track: lecture 4 Today: modules The idea of modules What's the idea behind a "module"? Package up code so other people/programs can use it Control what parts of code are part of the interface

More information

Derek Dreyer. WG2.8 Meeting, Iceland July 16-20, 2007

Derek Dreyer. WG2.8 Meeting, Iceland July 16-20, 2007 Why Applicative Functors Matter Derek Dreyer Toyota Technological Institute at Chicago WG2.8 Meeting, Iceland July 16-20, 2007 Matthias Felleisen Gets In a Good Jab Matthias Felleisen, POPL PC Chair report,

More information

CS558 Programming Languages

CS558 Programming Languages CS558 Programming Languages Winter 2017 Lecture 9b Andrew Tolmach Portland State University 1994-2017 Programming in the large Language features for modularity are crucial for writing large programs Idea:

More information

Introduction to OCaml

Introduction to OCaml Fall 2018 Introduction to OCaml Yu Zhang Course web site: http://staff.ustc.edu.cn/~yuzhang/tpl References Learn X in Y Minutes Ocaml Real World OCaml Cornell CS 3110 Spring 2018 Data Structures and Functional

More information

Runtime types

Runtime types OCaml@LexiFi, Runtime types LexiFi March 2017 Bloomberg/LexiFi workshop OCaml and LexiFi LexiFi has been (happily) using OCaml since 2001. Strong involvment in the OCaml ecosystem: Member of the OCaml

More information

F-ing Applicative Functors

F-ing Applicative Functors F-ing Applicative Functors Andreas Rossberg, Google Claudio Russo, MSR Derek Dreyer, MPI-SWS ML Workshop, Copenhagen 2012/09/13 The Functor Schism The Functor Schism SML: generative functors return fresh

More information

Outline. Introduction Concepts and terminology The case for static typing. Implementing a static type system Basic typing relations Adding context

Outline. Introduction Concepts and terminology The case for static typing. Implementing a static type system Basic typing relations Adding context Types 1 / 15 Outline Introduction Concepts and terminology The case for static typing Implementing a static type system Basic typing relations Adding context 2 / 15 Types and type errors Type: a set of

More information

CIS 120 Midterm I February 16, 2015 SOLUTIONS

CIS 120 Midterm I February 16, 2015 SOLUTIONS CIS 120 Midterm I February 16, 2015 SOLUTIONS 1 1. Substitution semantics (18 points) Circle the final result of simplifying the following OCaml expressions, or Infinite loop if there is no final answer.

More information

CIS 120 Midterm I October 2, Name (printed): Username (login id):

CIS 120 Midterm I October 2, Name (printed): Username (login id): CIS 120 Midterm I October 2, 2015 Name (printed): Username (login id): My signature below certifies that I have complied with the University of Pennsylvania s Code of Academic Integrity in completing this

More information

02157 Functional Programming. Michael R. Ha. Lecture 2: Functions, Types and Lists. Michael R. Hansen

02157 Functional Programming. Michael R. Ha. Lecture 2: Functions, Types and Lists. Michael R. Hansen Lecture 2: Functions, Types and Lists nsen 1 DTU Compute, Technical University of Denmark Lecture 2: Functions, Types and Lists MRH 13/09/2018 Outline Functions as first-class citizens Types, polymorphism

More information

Modular Module Systems: a survey

Modular Module Systems: a survey Modular Module Systems: a survey Christopher League LIU Brooklyn Northeast Scala Symposium 9 March 2012 Miran Lipovača, Learn You a Haskell for Great Good! http://learnyouahaskell.com/ (By-NC-SA) What

More information

Introduction to ML. Mooly Sagiv. Cornell CS 3110 Data Structures and Functional Programming

Introduction to ML. Mooly Sagiv. Cornell CS 3110 Data Structures and Functional Programming Introduction to ML Mooly Sagiv Cornell CS 3110 Data Structures and Functional Programming The ML Programming Language General purpose programming language designed by Robin Milner in 1970 Meta Language

More information

Modular implicits for OCaml how to assert success. Gallium Seminar,

Modular implicits for OCaml how to assert success. Gallium Seminar, Modular implicits for OCaml how to assert success Jacques Garrigue Nagoya University Frédéric Bour Sponsored by Jane Street LLC Gallium Seminar, 14-03-2016 Garrigue & Bour Mdular implicits and success

More information

CMSC 330: Organization of Programming Languages

CMSC 330: Organization of Programming Languages CMSC 330: Organization of Programming Languages CMSC330 Fall 2017 OCaml Data Types CMSC330 Fall 2017 1 OCaml Data So far, we ve seen the following kinds of data Basic types (int, float, char, string) Lists

More information

Abram Hindle Kitchener Waterloo Perl Monger October 19, 2006

Abram Hindle Kitchener Waterloo Perl Monger   October 19, 2006 OCaml Tutorial Abram Hindle Kitchener Waterloo Perl Monger http://kw.pm.org abez@abez.ca October 19, 2006 Abram Hindle 1 OCaml Functional Language Multiple paradigms: Imperative, Functional, Object Oriented

More information

CSE 341 Section 5. Winter 2018

CSE 341 Section 5. Winter 2018 CSE 341 Section 5 Winter 2018 Midterm Review! Variable Bindings, Shadowing, Let Expressions Boolean, Comparison and Arithmetic Operations Equality Types Types, Datatypes, Type synonyms Tuples, Records

More information

Dialects of ML. CMSC 330: Organization of Programming Languages. Dialects of ML (cont.) Features of ML. Functional Languages. Features of ML (cont.

Dialects of ML. CMSC 330: Organization of Programming Languages. Dialects of ML (cont.) Features of ML. Functional Languages. Features of ML (cont. CMSC 330: Organization of Programming Languages OCaml 1 Functional Programming Dialects of ML ML (Meta Language) Univ. of Edinburgh,1973 Part of a theorem proving system LCF The Logic of Computable Functions

More information

CSCI-GA Scripting Languages

CSCI-GA Scripting Languages CSCI-GA.3033.003 Scripting Languages 12/02/2013 OCaml 1 Acknowledgement The material on these slides is based on notes provided by Dexter Kozen. 2 About OCaml A functional programming language All computation

More information

Programming in Standard ML: Continued

Programming in Standard ML: Continued Programming in Standard ML: Continued Specification and Verification with Higher-Order Logic Arnd Poetzsch-Heffter (Slides by Jens Brandt) Software Technology Group Fachbereich Informatik Technische Universität

More information

ML Type Inference and Unification. Arlen Cox

ML Type Inference and Unification. Arlen Cox ML Type Inference and Unification Arlen Cox Research Goals Easy to use, high performance parallel programming Primary contributions in backend and runtime Need a front end to target backend ML offers ease

More information

CMSC 330: Organization of Programming Languages. OCaml Imperative Programming

CMSC 330: Organization of Programming Languages. OCaml Imperative Programming CMSC 330: Organization of Programming Languages OCaml Imperative Programming CMSC330 Fall 2017 1 So Far, Only Functional Programming We haven t given you any way so far to change something in memory All

More information

Typed Racket: Racket with Static Types

Typed Racket: Racket with Static Types Typed Racket: Racket with Static Types Version 5.0.2 Sam Tobin-Hochstadt November 6, 2010 Typed Racket is a family of languages, each of which enforce that programs written in the language obey a type

More information

Cornell University 12 Oct Solutions. (a) [9 pts] For each of the 3 functions below, pick an appropriate type for it from the list below.

Cornell University 12 Oct Solutions. (a) [9 pts] For each of the 3 functions below, pick an appropriate type for it from the list below. Cornell University 12 Oct 2006 Solutions 1. Types, Polymorphism [14 pts] (parts a b) (a) [9 pts] For each of the 3 functions below, pick an appropriate type for it from the list below. i. fun f x y = (y,

More information

CIS 120 Final Exam May 7, Name (printed): Pennkey (login id):

CIS 120 Final Exam May 7, Name (printed): Pennkey (login id): CIS 120 Final Exam May 7, 2014 Name (printed): Pennkey (login id): My signature below certifies that I have complied with the University of Pennsylvania s Code of Academic Integrity in completing this

More information

The Typed Racket Guide

The Typed Racket Guide The Typed Racket Guide Version 5.3.6 Sam Tobin-Hochstadt and Vincent St-Amour August 9, 2013 Typed Racket is a family of languages, each of which enforce

More information

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques (CIS120) Lecture 9 Jan 30, 2013 Abstract Types: Sets Announcements Homework 3 is available on the web Due MONDAY, February 4 th at 11:59:59pm PracRce with BSTs, generic

More information

SNU Programming Language Theory

SNU Programming Language Theory SNU 4541.574 Programming Language Theory Polymorphism Polymorphism We encountered the concept of polymorphism very briefly last time. Let s look at it now in a bit more detail. # let rec last l = match

More information

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

A Fourth Look At ML. Chapter Eleven Modern Programming Languages, 2nd ed. 1 A Fourth Look At ML Chapter Eleven Modern Programming Languages, 2nd ed. 1 Type Definitions Predefined, but not primitive in ML: datatype bool = true false; Type constructor for lists: datatype 'element

More information

Mutation. COS 326 David Walker Princeton University

Mutation. COS 326 David Walker Princeton University Mutation COS 326 David Walker Princeton University Mutation? 2 Thus far We have considered the (almost) purely functional subset of Ocaml. We ve had a few side effects: printing & raising exceptions. Two

More information

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

CSC/MAT-220: Lab 6. Due: 11/26/2018 CSC/MAT-220: Lab 6 Due: 11/26/2018 In Lab 2 we discussed value and type bindings. Recall, value bindings bind a value to a variable and are intended to be static for the life of a program. Type bindings

More information

Programming Languages and Techniques (CIS120e)

Programming Languages and Techniques (CIS120e) Programming Languages and Techniques (CIS120e) Lecture 7 Sep 15, 2010 Binary Search Trees (Part II), Generics Announcements Homework 2 is due tonight at 11:59:59pm. Homework 3 will be available on the

More information

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques (CIS120) Lecture 8 Feb 5, 2014 Abstract Types: Sets Modules and Interfaces Homework 3 is available Announcements Due TUESDAY, February 11 th at 11:59:59pm PracSce with

More information

Substructural Typestates

Substructural Typestates Programming Languages meets Program Verification 2014 Substructural Typestates Filipe Militão (CMU & UNL) Jonathan Aldrich (CMU) Luís Caires (UNL) Motivation! File file = new File( out.txt );! file.write(

More information

Types, Semantics, and Programming Languages (IK3620)

Types, Semantics, and Programming Languages (IK3620) Types, Semantics, and Programming Languages (IK3620) Exercises for Module 1 Operational semantics and the lambda calculus Version 1.02 David Broman KTH Royal Institute of Technology dbro@kth.se October

More information

CMSC 330: Organization of Programming Languages. OCaml Imperative Programming

CMSC 330: Organization of Programming Languages. OCaml Imperative Programming CMSC 330: Organization of Programming Languages OCaml Imperative Programming CMSC330 Spring 2018 1 So Far, Only Functional Programming We haven t given you any way so far to change something in memory

More information

Introduction to ML. Mooly Sagiv. Cornell CS 3110 Data Structures and Functional Programming

Introduction to ML. Mooly Sagiv. Cornell CS 3110 Data Structures and Functional Programming Introduction to ML Mooly Sagiv Cornell CS 3110 Data Structures and Functional Programming The ML Programming Language General purpose programming language designed by Robin Milner in 1970 Meta Language

More information

L3 Programming September 19, OCaml Cheatsheet

L3 Programming September 19, OCaml Cheatsheet OCaml Cheatsheet Note: this document comes from a previous course (by Sylvain Schimdt). The explanations of the OCaml syntax in this sheet are by no means intended to be complete or even sufficient; check

More information

Introduction to ML. Mooly Sagiv. Cornell CS 3110 Data Structures and Functional Programming

Introduction to ML. Mooly Sagiv. Cornell CS 3110 Data Structures and Functional Programming Introduction to ML Mooly Sagiv Cornell CS 3110 Data Structures and Functional Programming Typed Lambda Calculus Chapter 9 Benjamin Pierce Types and Programming Languages Call-by-value Operational Semantics

More information

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

CMSC 330: Organization of Programming Languages. Functional Programming with Lists CMSC 330: Organization of Programming Languages Functional Programming with Lists 1 Lists in OCaml The basic data structure in OCaml Lists can be of arbitrary length Implemented as a linked data structure

More information

SML Style Guide. Last Revised: 31st August 2011

SML Style Guide. Last Revised: 31st August 2011 SML Style Guide Last Revised: 31st August 2011 It is an old observation that the best writers sometimes disregard the rules of rhetoric. When they do so, however, the reader will usually find in the sentence

More information

CMSC 631. Functional Programming with OCaml

CMSC 631. Functional Programming with OCaml CMSC 631 Functional Programming with OCaml 1 Background ML (Meta Language) Univ. of Edinburgh, 1973 Part of a theorem proving system LCF The Logic of Computable Functions SML/NJ (Standard ML of New Jersey)

More information

FUNCTIONAL PROGRAMMING NO.9 TYPE AND CLASS. Tatsuya Hagino

FUNCTIONAL PROGRAMMING NO.9 TYPE AND CLASS. Tatsuya Hagino 1 FUNCTIONAL PROGRAMMING NO.9 TYPE AND CLASS Tatsuya Hagino hagino@sfc.keio.ac.jp 2 Static Type Checking and Type Inference Type a set of values Bool = { True, False } Char = { 'a', 'b',... } Int = {...

More information

Lecture 19: Signatures, Structures, and Type Abstraction

Lecture 19: Signatures, Structures, and Type Abstraction 15-150 Lecture 19: Signatures, Structures, and Type Abstraction Lecture by Dan Licata March 27, 2012 In these lectures, we will discuss the use of the ML module system for structuring large programs. Key

More information

Whidbey Enhancements to C# Jeff Vaughan MSBuild Team July 21, 2004

Whidbey Enhancements to C# Jeff Vaughan MSBuild Team July 21, 2004 Whidbey Enhancements to C# Jeff Vaughan MSBuild Team July 21, 2004 Outline Practical Partial types Static classes Extern and the namespace alias qualifier Cool (and practical too) Generics Nullable Types

More information

Notes on specifying user defined types

Notes on specifying user defined types Notes on specifying user defined types data Exp = While Exp Exp Bool Bool If Exp Exp Exp Int Int Add Exp Exp Sub Exp Exp Mul Exp Exp Div Exp Exp Leq Exp Exp Char Char Ceq Exp Exp Pair Exp Exp Fst Exp Snd

More information

CS153: Compilers Lecture 14: Type Checking

CS153: Compilers Lecture 14: Type Checking CS153: Compilers Lecture 14: Type Checking Stephen Chong https://www.seas.harvard.edu/courses/cs153 Announcements Project 4 out Due Thursday Oct 25 (7 days) Project 5 out Due Tuesday Nov 13 (26 days) Project

More information

Functors signature Order = sig functor name type elem (structname:signature) = structure definition; val le : elem*elem -> bool end; elem

Functors signature Order = sig functor name type elem (structname:signature) = structure definition; val le : elem*elem -> bool end; elem Functors The general form of a functor is functor name (structname:signature) = structure definition; This functor will create a specific version of the structure definition using the structure parameter

More information

TYPE INFERENCE. François Pottier. The Programming Languages Mentoring ICFP August 30, 2015

TYPE INFERENCE. François Pottier. The Programming Languages Mentoring ICFP August 30, 2015 TYPE INFERENCE François Pottier The Programming Languages Mentoring Workshop @ ICFP August 30, 2015 What is type inference? What is the type of this OCaml function? let f verbose msg = if verbose then

More information

CSE341: Programming Languages Lecture 11 Type Inference. Dan Grossman Spring 2016

CSE341: Programming Languages Lecture 11 Type Inference. Dan Grossman Spring 2016 CSE341: Programming Languages Lecture 11 Type Inference Dan Grossman Spring 2016 Type-checking (Static) type-checking can reject a program before it runs to prevent the possibility of some errors A feature

More information

Topics Covered Thus Far CMSC 330: Organization of Programming Languages

Topics Covered Thus Far CMSC 330: Organization of Programming Languages Topics Covered Thus Far CMSC 330: Organization of Programming Languages Names & Binding, Type Systems Programming languages Ruby Ocaml Lambda calculus Syntax specification Regular expressions Context free

More information

Parametric types. map: ( a (a b) a list b list. filter: ( a bool) a list a list. Why? a and b are type variables!

Parametric types. map: ( a (a b) a list b list. filter: ( a bool) a list a list. Why? a and b are type variables! What is the deal with a? Parametric types aka: what s up with those a? These meta-functions have strange types: map: ( a b) a list b list filter: ( a bool) a list a list Why? Polymorphism Poly = many,

More information

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques (CIS120) Lecture 10 February 2, 2018 Abstract types: Sets Chapter 10 Announcements Homework 3 due Tuesday at 11:59:59pm Midterm 1 Friday, February 9, in class Covers

More information

Metaprogramming assignment 3

Metaprogramming assignment 3 Metaprogramming assignment 3 Optimising embedded languages Due at noon on Thursday 29th November 2018 This exercise uses the BER MetaOCaml compiler, which you can install via opam. The end of this document

More information

Types, Type Inference and Unification

Types, Type Inference and Unification Types, Type Inference and Unification Mooly Sagiv Slides by Kathleen Fisher and John Mitchell Cornell CS 6110 Summary (Functional Programming) Lambda Calculus Basic ML Advanced ML: Modules, References,

More information

Overloading, Type Classes, and Algebraic Datatypes

Overloading, Type Classes, and Algebraic Datatypes Overloading, Type Classes, and Algebraic Datatypes Delivered by Michael Pellauer Arvind Computer Science and Artificial Intelligence Laboratory M.I.T. September 28, 2006 September 28, 2006 http://www.csg.csail.mit.edu/6.827

More information

The Typed Racket Reference

The Typed Racket Reference The Typed Racket Reference Version 5.1 Sam Tobin-Hochstadt February 14, 2011 #lang typed/racket/base #lang typed/racket 1 1 Type Reference Any Any Racket value. All other types are subtypes of Any. Nothing

More information

Introduction to Delimited Continuations. Typing Printf. Printf. Kenichi Asai. Ochanomizu University. April 13, 2008

Introduction to Delimited Continuations. Typing Printf. Printf. Kenichi Asai. Ochanomizu University. April 13, 2008 Introduction to Delimited Continuations Typing Printf Printf Kenichi Asai Ochanomizu University April 13, 2008 Outline of the talk times (introduction) (1) in Direct Style with exception (2) in Continuation-Passing

More information

Specification and Verification in Higher Order Logic

Specification and Verification in Higher Order Logic Specification and Verification in Higher Order Logic Prof. Dr. K. Madlener 13. April 2011 Prof. Dr. K. Madlener: Specification and Verification in Higher Order Logic 1 Chapter 1 Functional Programming:

More information

ECE 449 OOP and Computer Simulation Lecture 12 Resource Management II

ECE 449 OOP and Computer Simulation Lecture 12 Resource Management II ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 1/62 ECE 449 OOP and Computer Simulation Lecture 12 Resource Management II Professor Jia Wang Department of Electrical

More information

Type Hierarchy. Comp-303 : Programming Techniques Lecture 9. Alexandre Denault Computer Science McGill University Winter 2004

Type Hierarchy. Comp-303 : Programming Techniques Lecture 9. Alexandre Denault Computer Science McGill University Winter 2004 Type Hierarchy Comp-303 : Programming Techniques Lecture 9 Alexandre Denault Computer Science McGill University Winter 2004 February 16, 2004 Lecture 9 Comp 303 : Programming Techniques Page 1 Last lecture...

More information

COEN244: Class & function templates

COEN244: Class & function templates COEN244: Class & function templates Aishy Amer Electrical & Computer Engineering Templates Function Templates Class Templates Outline Templates and inheritance Introduction to C++ Standard Template Library

More information

G Programming Languages Spring 2010 Lecture 8. Robert Grimm, New York University

G Programming Languages Spring 2010 Lecture 8. Robert Grimm, New York University G22.2110-001 Programming Languages Spring 2010 Lecture 8 Robert Grimm, New York University 1 Review Last time Types Fun with O Caml 2 Outline Modules Sources: PLP, 3.3.4, 3.3.5, 3.7 Barrett. Lecture notes,

More information