Last active
May 25, 2019 18:48
-
-
Save Pitometsu/d5f98078de340ccfb1f929a0da9aac73 to your computer and use it in GitHub Desktop.
Type Classes & implicit instantination in OCaml
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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