Concepts of programming languages - OCaml - Functors and ...OCaml-FunctorsandModules...
Transcript of Concepts of programming languages - OCaml - Functors and ...OCaml-FunctorsandModules...
[Faculty of ScienceInformation and Computing
Sciences]1
Concepts of programming languagesOCaml - Functors and Modules
Chiel van Griethuijsen, Maxwell Hessey, MarinusOosters, Jasper Robeer and Quiri Passchier
[Faculty of ScienceInformation and Computing
Sciences]2
Ocaml is a
▶ Multi paradigm▶ Functional, imperative and object-oriented
▶ Strict▶ Statically typed▶ Garbage collected
Language
[Faculty of ScienceInformation and Computing
Sciences]3
Featuring:
▶ Type Inference▶ Parametric polymorphism▶ Structural subtyping▶ Pattern matching
AndModules, User defined Types and Functors, which wewill focus on
[Faculty of ScienceInformation and Computing
Sciences]4
Contents
▶ Contents▶ Introduction▶ Modules▶ Types and Variants▶ Modules with Types▶ Functors
[Faculty of ScienceInformation and Computing
Sciences]5
Contents
▶ Contents▶ Introduction▶ Modules▶ Types and Variants▶ Modules with Types▶ Functors
[Faculty of ScienceInformation and Computing
Sciences]6
Introduction
Who uses OCaml and why?
▶ Facebook (open scource)▶ Hack, staticaly typed PHP (compiler)▶ Flow, static analyser JavaScript▶ Infer, static analyser Java, C and Objective-C
▶ Mentioned in this course:▶ Coq, a formal proof management system▶ WebAssembly
Etc. Industrial strength language
[Faculty of ScienceInformation and Computing
Sciences]7
Introduction
▶ Summary concepts we will build on▶ Questions on the basics?
[Faculty of ScienceInformation and Computing
Sciences]8
Contents
▶ Contents▶ Introduction▶ Modules▶ Types and Variants▶ Modules with Types▶ Functors
[Faculty of ScienceInformation and Computing
Sciences]9
Modules — Basics
Functional namespaces and classes.
filename.ml = Modulename
or Multiple modules in one files using:
module <name> = struct<implement>
end
This is a structural module
Real power comes with signatures and functors
[Faculty of ScienceInformation and Computing
Sciences]10
Modules — Open
Lets define two small modules.
module Add = structlet add x y = x + y ;;
end
module DifferentAdd = structlet add x y = x * y ;;
end
[Faculty of ScienceInformation and Computing
Sciences]11
Modules — Open
And see how we can use them
open Add ;;
let a = add 2 5 ;; (* a = 7*)
let b = let open DifferentAdd inadd 2 5 ;; (* b = 10 *)
let c = DifferentAdd.(add 2 5) ;; (* c = 10 *)
[Faculty of ScienceInformation and Computing
Sciences]12
Modules — Include
module Extended_YourModule = structinclude YourModule
let extraYourModulefunction x y = … ;;end ;;
Override by declaration order
[Faculty of ScienceInformation and Computing
Sciences]13
Contents
▶ Contents▶ Introduction▶ Modules▶ Types and Variants▶ Modules with Types▶ Functors
[Faculty of ScienceInformation and Computing
Sciences]14
Types and Variants
Let’s take a look at the types of OCaml
▶ Built-in types, user defined types and variants▶ Static type checking and type inference
[Faculty of ScienceInformation and Computing
Sciences]15
Types and Variants
OCaml has a wide variety of built-in types
▶ Integers, floating-points, chars, booleans, strings, …▶ Lists▶ Tuples▶ User defined types
We will take a look at tuples and user defined types first
Then we will discuss the type inference system
[Faculty of ScienceInformation and Computing
Sciences]15
Types and Variants
OCaml has a wide variety of built-in types
▶ Integers, floating-points, chars, booleans, strings, …▶ Lists▶ Tuples▶ User defined types
We will take a look at tuples and user defined types first
Then we will discuss the type inference system
[Faculty of ScienceInformation and Computing
Sciences]16
Types and Variants — Tuples
Tuples are built-in data types in OCaml
let person = ("Henry", 25, 180) ;;val person : string * int * int
[Faculty of ScienceInformation and Computing
Sciences]17
Types and Variants — User Defined Types
User defined types can be defined using the type keyword
▶ Defining a new name for types:
type coordinates = int * int ;;
▶ Defining enums:
type colors = Red | Green | Blue ;;
[Faculty of ScienceInformation and Computing
Sciences]17
Types and Variants — User Defined Types
User defined types can be defined using the type keyword
▶ Defining a new name for types:
type coordinates = int * int ;;
▶ Defining enums:
type colors = Red | Green | Blue ;;
[Faculty of ScienceInformation and Computing
Sciences]17
Types and Variants — User Defined Types
User defined types can be defined using the type keyword
▶ Defining a new name for types:
type coordinates = int * int ;;
▶ Defining enums:
type colors = Red | Green | Blue ;;
[Faculty of ScienceInformation and Computing
Sciences]18
Types and Variants — User Defined Types
User defined types can be defined using the type keyword
▶ Defining variants:
type interval =Interval of int * int| Empty ;;
let a = Interval (0, 10) ;;let b = Empty ;;
[Faculty of ScienceInformation and Computing
Sciences]19
Types and Variants — Pattern Matching
We can perform pattern matching on variants usingfunction
let inside v = function| Interval (min,max) -> v >= min && v <= max| Empty -> true ;;
[Faculty of ScienceInformation and Computing
Sciences]20
Types and Variants — Pattern Matching
We can perform pattern matching on variants using match
let inside_m v i = match i with| Interval (min,max) -> v >= min && v <= max| Empty -> true ;;
[Faculty of ScienceInformation and Computing
Sciences]21
Static Type Checking
OCaml uses a compilation pipeline, where the type inferenceand static type checking are part of the second stage
Figure 1: OCaml Compilation Pipeline
[Faculty of ScienceInformation and Computing
Sciences]22
Static Type Checking
We need a valid AST as prerequisite
Type checking is performed as three steps:
▶ Automatic type inference▶ Module system▶ Explicit subtyping
The results of the type checking pass can be seen byinvoking the OCaml compiler with ocamlc -i
[Faculty of ScienceInformation and Computing
Sciences]22
Static Type Checking
We need a valid AST as prerequisite
Type checking is performed as three steps:
▶ Automatic type inference▶ Module system▶ Explicit subtyping
The results of the type checking pass can be seen byinvoking the OCaml compiler with ocamlc -i
[Faculty of ScienceInformation and Computing
Sciences]23
Type Inference
OCamls’ type inference is based on the Hindley-Milner typesystem
Which infers the most general type for an expressionwithout requiring any explicit type annotations
[Faculty of ScienceInformation and Computing
Sciences]24
Type Inference — Hindley-Milner Type System
Described in papers by Hindley (1969) and Milner (1978)
Used by ML, OCaml, Haskell and F# (and other functionallanguages)
Formalizes the intuition that a type can be deduced by thefunctionality that it supports
It looks through the body of a function and computes aconstraint set based on how each value is used
[Faculty of ScienceInformation and Computing
Sciences]25
Type Inference — Hindley-Milner Type System
The increment function as an example
let incr x = x + 1 ;;
Let’s assume that we know the type of + : int -> int ->int
Then we can deduce that the type of x and 1 in the incrfunction must be of type int
The type of the function as a whole is then int -> int
[Faculty of ScienceInformation and Computing
Sciences]25
Type Inference — Hindley-Milner Type System
The increment function as an example
let incr x = x + 1 ;;
Let’s assume that we know the type of + : int -> int ->int
Then we can deduce that the type of x and 1 in the incrfunction must be of type int
The type of the function as a whole is then int -> int
[Faculty of ScienceInformation and Computing
Sciences]25
Type Inference — Hindley-Milner Type System
The increment function as an example
let incr x = x + 1 ;;
Let’s assume that we know the type of + : int -> int ->int
Then we can deduce that the type of x and 1 in the incrfunction must be of type int
The type of the function as a whole is then int -> int
[Faculty of ScienceInformation and Computing
Sciences]26
Contents
▶ Contents▶ Introduction▶ Modules▶ Types and Variants▶ Modules with Types▶ Functors
[Faculty of ScienceInformation and Computing
Sciences]27
Modules with Types
▶ Signatures, Interface or module type▶ Specify accessible components and their types▶ Public
module type SIGNAME = sig definitions end
▶ type▶ val▶ exception
[Faculty of ScienceInformation and Computing
Sciences]27
Modules with Types
▶ Signatures, Interface or module type▶ Specify accessible components and their types▶ Public
module type SIGNAME = sig definitions end
▶ type▶ val▶ exception
[Faculty of ScienceInformation and Computing
Sciences]27
Modules with Types
▶ Signatures, Interface or module type▶ Specify accessible components and their types▶ Public
module type SIGNAME = sig definitions end
▶ type▶ val▶ exception
[Faculty of ScienceInformation and Computing
Sciences]28
Modules with Types
Create a signature for integer intervals
module type INTINTERVAL = sigtype interval = Interval of int * int | Emptyval create: int -> int -> interval
end ;;
module IntInterval:INTINTERVAL = structtype interval = Interval of int * int | Emptylet e = Emptylet create low high =
if low > high then e else Interval (low,high)end ;;
[Faculty of ScienceInformation and Computing
Sciences]28
Modules with Types
Create a signature for integer intervals
module type INTINTERVAL = sigtype interval = Interval of int * int | Emptyval create: int -> int -> interval
end ;;
module IntInterval:INTINTERVAL = structtype interval = Interval of int * int | Emptylet e = Emptylet create low high =
if low > high then e else Interval (low,high)end ;;
[Faculty of ScienceInformation and Computing
Sciences]29
Modules with Types
Types in signatures can be abstract
module type INTINTERVAL = sigtype intervalval create: int -> int -> interval
end ;;
module IntInterval:INTINTERVAL = structtype interval = Interval of int *int | Emptylet e = Emptylet create low high =
if low>high then e else Interval (low,high)end ;;
e not accessible
[Faculty of ScienceInformation and Computing
Sciences]30
Modules with Types
▶ Documents▶ Nesting▶ Build-in modules
List.length [1,2,3,4] ;;String.length "abcdef" ;;
[Faculty of ScienceInformation and Computing
Sciences]30
Modules with Types
▶ Documents▶ Nesting▶ Build-in modules
List.length [1,2,3,4] ;;String.length "abcdef" ;;
[Faculty of ScienceInformation and Computing
Sciences]31
Contents
▶ Contents▶ Introduction▶ Modules▶ Types and Variants▶ Modules with Types▶ Functors
[Faculty of ScienceInformation and Computing
Sciences]32
A change of plans
▶ What if we wanted a interval of names (strings).▶ We have to rewrite code.
▶ Oops.. We should have used functors.
[Faculty of ScienceInformation and Computing
Sciences]32
A change of plans
▶ What if we wanted a interval of names (strings).▶ We have to rewrite code.
▶ Oops.. We should have used functors.
[Faculty of ScienceInformation and Computing
Sciences]33
Functors
▶ A functor is to modules as..▶ .. a function is to variables.▶ function (variable) = variable▶ functor (module) = module▶ Different to haskell!
[Faculty of ScienceInformation and Computing
Sciences]34
A not-so-useful example
For functions:
▶ We can define a variable of type int:
let three = 3 ;;
▶ Then apply increment to get a new variable of type int:
let four = increment three ;;
[Faculty of ScienceInformation and Computing
Sciences]35
A not-so-useful example
For functors:
▶ We define a module of type X_int:
module Three = structlet x = 3
end ;;
▶ Then apply Increment to get a new module of typeX_int:
module Four = Increment(Three) ;;
[Faculty of ScienceInformation and Computing
Sciences]36
Functor syntax
▶ Recall that a function can be defined by:
let increment x = x + 1 ;;
▶ We can add type constraints:
let increment (x : int) : int = x + 1;;
▶ For functors this is:
module Increment (M : X_int) : X_int = structlet x = M.x + 1
end;;
[Faculty of ScienceInformation and Computing
Sciences]37
Creating intervals — The plan
▶ We want to create intervals of a set.▶ The elements of the set must be comparable.▶ We define a signature with this feature.▶ Using functors, we may create intervals of any type, aslong as it is comparable.
[Faculty of ScienceInformation and Computing
Sciences]38
Creating intervals — Preparatation
▶ Our module signature:
module type COMPARABLE = sigtype ctval compare : ct -> ct -> int
end ;;
ct here for readability. t is used in standard modules likeString
[Faculty of ScienceInformation and Computing
Sciences]38
Creating intervals — Preparatation
▶ Our module signature:
module type COMPARABLE = sigtype ctval compare : ct -> ct -> int
end ;;
ct here for readability. t is used in standard modules likeString
[Faculty of ScienceInformation and Computing
Sciences]39
Creating intervals — Code
▶ The functor to make intervals:
module Make_interval(Endpoint : COMPARABLE) = struct
type it = | Interval of Endpoint.ct * Endpoint.ct| Empty
let create low high =if Endpoint.compare low high > 0 then Emptyelse Interval (low,high)
end ;;
[Faculty of ScienceInformation and Computing
Sciences]40
Creating intervals — Result
module Int_interval = Make_interval(Int) ;;module String_interval = Make_interval(String) ;;
[Faculty of ScienceInformation and Computing
Sciences]41
A problem— Bypassing create
▶ What does this give?
let i1 = Int_interval.Interval (3,1)let i2 = Int_interval.create 3 1
i1 = Int_interval.Interval (3, 1)i2 = Int_interval.Empty
Problem is calling Interval directly.
[Faculty of ScienceInformation and Computing
Sciences]41
A problem— Bypassing create
▶ What does this give?
let i1 = Int_interval.Interval (3,1)let i2 = Int_interval.create 3 1
i1 = Int_interval.Interval (3, 1)i2 = Int_interval.Empty
Problem is calling Interval directly.
[Faculty of ScienceInformation and Computing
Sciences]41
A problem— Bypassing create
▶ What does this give?
let i1 = Int_interval.Interval (3,1)let i2 = Int_interval.create 3 1
i1 = Int_interval.Interval (3, 1)i2 = Int_interval.Empty
Problem is calling Interval directly.
[Faculty of ScienceInformation and Computing
Sciences]42
A solution — Abstract Functors
▶ Define an Interface (a signature) for intervals.▶ Bind the result of the functor.
module Make_interval(Endpoint : COMPARABLE) :INTERVAL_INTERFACE = struct...
end
[Faculty of ScienceInformation and Computing
Sciences]43
Designing an interval signature:
What does an interval need?
▶ A type of interval▶ A function with which to create intervals▶ The argument type of this function
module type INTERVAL_INTERFACE = sigtype ittype endpointval create : endpoint -> endpoint -> it
end ;;
The type definition of ‘it’ is hidden,Int_interval.Interval cannot be called.
[Faculty of ScienceInformation and Computing
Sciences]43
Designing an interval signature:
What does an interval need?
▶ A type of interval▶ A function with which to create intervals▶ The argument type of this function
module type INTERVAL_INTERFACE = sigtype ittype endpointval create : endpoint -> endpoint -> it
end ;;
The type definition of ‘it’ is hidden,Int_interval.Interval cannot be called.
[Faculty of ScienceInformation and Computing
Sciences]44
Finishing touches
Our functor has to define endpoint. To keep endpointaccessible it’s type is made explicity visible.
module Make_interval(Endpoint : COMPARABLE) :(INTERVAL_INTERFACE with type endpoint = Endpoint.t)= struct
type endpoint = Endpoint.ttype t = | Interval of Endpoint.t * Endpoint.t
| Empty(*etc*)
end ;;
[Faculty of ScienceInformation and Computing
Sciences]45
Goal Achieved
Now create an interval module by:
module Int_interval = Make_interval(Int);;module String_interval = Make_interval(String);;
[Faculty of ScienceInformation and Computing
Sciences]46
A recap
▶ Modules bunch together code▶ Functors can create newmodules
[Faculty of ScienceInformation and Computing
Sciences]47
There is much more…
▶ Functors can be applicative or generative▶ In short:▶ Applying an applicative functor to the same modulegives the same results
▶ Generative functors create distinct results▶ Functors can be used to add type specific functionality
[Faculty of ScienceInformation and Computing
Sciences]48
I want to learn OCaml!
▶ The official site: ocaml.org▶ With exercises: 99 problems easy to hard▶ An interesting book to read at: realworldocaml.org▶ Examples in this presentation are based on or copiedfrom Real World Ocaml.
[Faculty of ScienceInformation and Computing
Sciences]49
Thank you for your attention.
[Faculty of ScienceInformation and Computing
Sciences]50