spacepaste

example.ml

  1.  
  2. open Batteries
  3. module type N = sig
  4. type t
  5. val make: unit -> t
  6. val add_to_self: t -> t -> unit
  7. val as_float: t -> float
  8. end
  9. module Int: N = struct
  10. type t = int ref
  11. let make () = ref 1
  12. let add_to_self x y = x := !x + !y
  13. let as_float = (!) |- float_of_int
  14. end
  15. module Float: N = struct
  16. type t = float ref
  17. let make () = ref 0.5
  18. let add_to_self x y = x := !x +. !y
  19. let as_float = (!) |- identity
  20. end
  21. let which_module = function
  22. | "float" -> (module Float: N)
  23. | "int" -> (module Int: N)
  24. | _ -> invalid_arg "which_module"
  25. let do_repetitive_work m x =
  26. let module C = (val m: N) in
  27. C.make () |> C.add_to_self x;
  28. C.add_to_self x x
  29. let () =
  30. let module C = (val (which_module Sys.argv.(1)): N) in
  31. let x = C.make () in
  32. do_repetitive_work (module C: N) x;
  33. C.as_float x |> Printf.printf "%g\n"
  34.  

error.txt

  1.  
  2. File "example.ml", line 31, characters 29-30:
  3. Error: This expression has type 'a but an expression was expected of type C.t
  4. The type constructor C.t would escape its scope
  5.