osiire’s blog

ふしぎなそふとやさん

ダックタイピング...

OCamlでは、特定の関数を持っている型を作ってごにょごにょする方法はいくつかあります。

(*- row多相 *)
# let touch animal : unit = animal#say;;
val touch : < say : unit; .. > -> unit = <fun>
(*- 構造的部分型 *)
# class type animal = object method say : unit end;;
class type animal = object method say : unit end
# let touch (a : animal) = a#say;;
val touch : animal -> unit = <fun>
# let duck = object method say = print_string "ga-" method other = "gu-" end;;
val duck : < other : string; say : unit > = <obj>
# touch (duck :> animal);;
ga-- : unit = ()
(* シグネチャー *)
# module type Animal = sig
    val say : unit -> unit
  end;;
module type Animal = sig val say : unit -> unit end
# let touch (module A : Animal) =
    A.say ();;
val touch : (module Animal) -> unit = <fun>
# touch (module struct let say () = print_string "ga-" end : Animal);;
ga-- : unit = ()