Le mercredi 07 décembre 2011 à 11:46 -0500, Alex Rubinsteyn a écrit :
> Cool! Thanks for writing this. Can you explain how defining a custom
> printer works? The new language features still bewilder me.
If you want to define a custom printer for a type named foo, you have to
define a function named string_of_foo. It must be in the same module as
foo. It takes as arguments printers for its type variables, the value to
print and returns a string.
For example, if your type is:
type ('a, 'b) foo
a custom printer for foo will have the signature:
val string_of_foo : ('a -> string) -> ('b -> string) -> ('a, 'b) foo -> string
For example:
module Id : sig
type t
val string_of_t : t -> string
val create : unit -> t
end = struct
type t = int
let string_of_t x = "<id=" ^ string_of_int x ^ ">"
let next = ref 0
let create () = incr next; !next
end
You may also want to use "show" in your custom printer. In order to tell
show to use the printers given as arguments, you must use type
parameters like that:
let string_of_foo (type a) (type b) string_of_a string_of_b (x : (a, b) foo) =
...
For example to export a generated printer for an abstract type:
module M : sig
type ('a, 'b) t
val string_of_t : ('a -> string) -> ('b -> string) -> ('a, 'b) t -> string
end = struct
type ('a, 'b) t = A of 'a | B of 'b
let string_of_t (type a) (type b) string_of_a string_of_b (x : (a, b) t) =
show x
end
Cheers,
--
Jérémie
--
Caml-list mailing list. Subscription management and archives:
https://sympa-roc.inria.fr/wws/info/caml-list
Beginner's list: http://groups.yahoo.com/group/ocaml_beginners
Bug reports: http://caml.inria.fr/bin/caml-bugs