Created
August 15, 2022 16:11
-
-
Save fccm/6513c0b6410c8827abd2c3c1b5aa1293 to your computer and use it in GitHub Desktop.
fake OO with variants
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
module A : sig | |
type u | |
val make: int -> int -> u | |
val f: u -> u | |
val p: u -> unit | |
end = struct | |
type u = { | |
a: int; | |
b: int; | |
} | |
let make a b = { a; b; } | |
let f u = { u with a = succ u.a } | |
let p u = Printf.printf " { %d %d }\n" u.a u.b | |
end | |
module B : sig | |
type v | |
val make: int -> int -> v | |
val f: v -> v | |
val p: v -> unit | |
end = struct | |
type v = { | |
c: int; | |
d: int; | |
} | |
let make c d = { c; d; } | |
let f v = { v with d = succ v.d } | |
let p v = Printf.printf " { %d %d }\n" v.c v.d | |
end | |
module C : sig | |
type w | |
val make: int -> int -> w | |
val f: w -> w | |
val p: w -> unit | |
end = struct | |
type w = { | |
e: int; | |
g: int; | |
} | |
let make e g = { e; g; } | |
let f w = { w with g = succ w.g } | |
let p w = Printf.printf " { %d %d }\n" w.e w.g | |
end | |
type t = | |
| A of A.u | |
| B of B.v | |
| C of C.w | |
let make_a a b = A (A.make a b) | |
let make_b c d = B (B.make c d) | |
let make_c e g = C (C.make e g) | |
let update = function | |
| A u -> A(A.f u) | |
| B v -> B(B.f v) | |
| C w -> C(C.f w) | |
let print = function | |
| A u -> A.p u | |
| B v -> B.p v | |
| C w -> C.p w | |
let () = | |
let a = make_a 1 2 in | |
let b = make_b 3 4 in | |
let c = make_c 5 6 in | |
let xs = [ a; b; c ] in | |
List.iter print xs; | |
print_newline (); | |
let xs = List.map update xs in | |
List.iter print xs; | |
;; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment