Skip to content

Instantly share code, notes, and snippets.

@jaymody
Created May 24, 2024 22:07
Show Gist options
  • Save jaymody/80c8b26a8b2c24f1d907b03b98d0662e to your computer and use it in GitHub Desktop.
Save jaymody/80c8b26a8b2c24f1d907b03b98d0662e to your computer and use it in GitHub Desktop.
Two different approaches to implementing some module that requires the polymorphic input type to be comparable. First method we explicitly must pass some comparison method. Second method we use a functor.
module MinContainer1 = struct
type 'a t =
{ cmp : 'a -> 'a -> int
; x : 'a option
}
let init cmp = { cmp; x = None }
let add { cmp; x } newx =
let x =
match x with
| None -> newx
| Some x -> if cmp newx x < 0 then newx else x
in
{ cmp; x = Some x }
;;
let get { x; _ } = Option.get x
end
let () =
let container = MinContainer1.init (fun a b -> a - b) in
[ 7; 3; -1; 4; -5; 5 ]
|> List.fold_left MinContainer1.add container
|> MinContainer1.get
|> string_of_int
|> print_endline
;;
module type Comparable = sig
type t
val compare : t -> t -> int
end
module MinContainer2 (T : Comparable) = struct
type t = T.t option
let init = None
let add t newx =
match t with
| None -> Some newx
| Some x -> Some (if T.compare newx x < 0 then newx else x)
;;
let get x = Option.get x
end
let () =
let module Mc2 = MinContainer2 (Int) in
let container = Mc2.init in
[ 7; 3; -1; 4; -5; 5 ]
|> List.fold_left Mc2.add container
|> Mc2.get
|> string_of_int
|> print_endline
;;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment