example.ml
- open Batteries
- module type N = sig
- type t
- val make: unit -> t
- val add_to_self: t -> t -> unit
- val as_float: t -> float
- end
- module Int: N = struct
- type t = int ref
- let make () = ref 1
- let add_to_self x y = x := !x + !y
- let as_float = (!) |- float_of_int
- end
- module Float: N = struct
- type t = float ref
- let make () = ref 0.5
- let add_to_self x y = x := !x +. !y
- let as_float = (!) |- identity
- end
- let which_module = function
- | "float" -> (module Float: N)
- | "int" -> (module Int: N)
- | _ -> invalid_arg "which_module"
- let do_repetitive_work m x =
- let module C = (val m: N) in
- C.make () |> C.add_to_self x;
- C.add_to_self x x
- let () =
- let module C = (val (which_module Sys.argv.(1)): N) in
- let x = C.make () in
- do_repetitive_work (module C: N) x;
- C.as_float x |> Printf.printf "%g\n"
error.txt
- File "example.ml", line 31, characters 29-30:
- Error: This expression has type 'a but an expression was expected of type C.t
- The type constructor C.t would escape its scope