Modules 2 ========= 1. Can we add a function to multiple modules at the same time? Arithmetic intervals: Range of integers 3, 4, 5, 6, 7 Closed interval of real numbers: all numbers between 3.2 and 4.8 All words in the dictionary between "compiler" and "language": "compressor", "docket", "floatation", ..., "compressors" - An interval is defined by two endpoints - We want to be able to answer the question: Is an element e contained in some interval intvl? contains : intvl -> t -> bool - Essential requirement: We need to be able to compare. module type Comparable = sig type t val compare : t -> t -> int (* compare x y < 0 iff x < y *) (* compare x y = 0 iff x = y *) (* compare x y > 0 iff x > y *) end module IntComparable : Comparable = ... module FloatComparable : Comparable = ... module StringComparable : Comparable = ... We want to be able to talk about "type t intvl" for any type t which is comparable. type int_intvl = Range of int * int let int_intvl_contains = ... type float_intvl = Range of float * float let float_intvl_contains = ... module Make_Interval (Endpoint : Comparable) = struct let (<=) x y = (Endpoint.compare x y <= 0) type intvl = Empty | Range of Endpoint.t * Endpoint.t let contains intvl x = match intvl with | Empty -> false | Range(lo, hi) -> lo <= x && x <= hi end module type Comparable = sig type t val compare : 'a -> 'a -> int (* compare x y < 0 iff x < y *) (* compare x y = 0 iff x = y *) (* compare x y > 0 iff x > y *) end;; module IntComparable : Comparable = struct type t = int let string_to_t s = Int.from_string s let compare x y = x - y end let x : IntComparable.t = 3 module Make_Interval (Endpoint : Comparable) = struct let (<=) x y = (Endpoint.compare x y <= 0) type intvl = Empty | Range of Endpoint.t * Endpoint.t let contains intvl x = match intvl with | Empty -> false | Range(lo, hi) -> lo <= x && x <= hi end