Skip to content

Instantly share code, notes, and snippets.

@Pitometsu
Last active May 25, 2019 18:48
Show Gist options
  • Save Pitometsu/d5f98078de340ccfb1f929a0da9aac73 to your computer and use it in GitHub Desktop.
Save Pitometsu/d5f98078de340ccfb1f929a0da9aac73 to your computer and use it in GitHub Desktop.
Type Classes & implicit instantination in OCaml
type 'u anySuch = { va: 'u ; to_string : 'u -> string };; (* type interface *)
type someSuch = Such : _ anySuch -> someSuch;; (* existential bounded by interface *)
type (_, 'g) anyInstance = { instance : 'g };; (* typeclass instance *)
type _ someInstance = Instance : (_, 'g) anyInstance -> 'g someInstance;; (* abstract typeclass *)
let anySuchInstance : (_, someSuch) anyInstance = { instance = Such { va = 6 ; to_string = string_of_int } };; (* implementation *)
let someSuchInstance : someSuch someInstance = Instance anySuchInstance;; (* type class existential *)
let f : someSuch someInstance -> string = function Instance i ->
match i.instance with Such e -> e.to_string e.va;; (* generic function *)
let () = f @@ someSuchInstance |> ignore;; (* abstract instantiation *)
(* But how can I instantiate `Such` instance from specific type, e.g. `int`, can type singletones be helpful there? *)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment