モジュールほどHaskellに近いわけではありませんが、オブジェクトクラスの階層上のクラスタイプは明確に説明されていません。
クラスタイプの定義を参照してください。
更新:実例:
type comparison = Lesser | Equal | Greater
class type comparable = object ('a)
method compareTo: 'a -> comparison
end ;;
class type textualizable = object
method toString: string
end ;;
(* this corresponds in Haskell to a multiparameter type class *)
class type ['b] printable = object ('a)
constraint 'b = #textualizable
method printWithPrefix: 'b -> unit
end ;;
class type ['b] comparableAndPrintable = object ('a)
inherit comparable
inherit ['b] printable
end ;;
(* -------------- *)
class textile (str_init:string): textualizable = object
val str = str_init
method toString = str
end ;;
class comparableAndPrintableImpl1 (x_init: int) = object (this:'a)
constraint 'a = 'b #comparableAndPrintable (* interface implementation requirement *)
constraint 'b = textualizable (* concrete type parameter *)
val x = x_init
method getx = x
method compareTo (that:'a) = let r = this#getx - that#getx in
match r with
| 0 -> Equal
| _ when r < 0 -> Lesser
| _ -> Greater
method printWithPrefix (pref: 'b) = Printf.printf "%s %d\n" pref#toString x
end ;;
let boxSort (pivot: #comparable) (lows, equals, highs) (x: #comparable) =
match x#compareTo pivot with
| Lesser -> x :: lows, equals, highs
| Equal -> lows, x :: equals, highs
| Greater -> lows, equals, x :: highs
;;
let rec qsort (li : #comparable list) =
match li with
[] | [_] -> li
| [a;b] -> (match a#compareTo b with
Lesser | Equal -> [a;b]
| Greater -> [b;a]
)
| x :: xs -> let (lows, equals, highs) = List.fold_left (boxSort x) ([], [], []) xs in
qsort lows @ (x :: equals) @ qsort highs
;;
let print_myList (prefix: 'a) (li: 'a #printable list) =
let print_it it = it#printWithPrefix prefix in
print_endline "\nlist: " ;
List.iter print_it li
;;
let intlist (lfrom: int) (lto: int) =
let open BatLazyList in
to_list (range lfrom lto) (* lazy range generator from BatLazyList *)
;;
let myComparableAndPrintableList =
List.map (new comparableAndPrintableImpl1) (List.rev (intlist 1 5))
;;
let myprefix = new textile "x ="
let sortAndPrint (li: 'a #comparableAndPrintable list) =
let sorted = qsort li in
print_myList myprefix li ;
print_myList myprefix sorted
;;
sortAndPrint myComparableAndPrintableList ;;
コンパイルしてリンクします:
ocamlfind ocamlc -package batteries -linkpkg test.ml -o test