Why does the% A specifier in F # printf not exist in OCaml printf?

In F # printf there is a %A format specifier that allows you to pass any type of F #, and it will be evaluated and printed.

As an example:

 type Result<'a> = | Failure | Success of 'a printf "%A" (Success "hello") // prints out 'Success "hello"' 

Where, obviously, Result<'a> not a built-in type.

I can declare a similar type in OCaml, but for Printf.printf there is no equivalent qualifier, instead I would have to implement my own function string_of_result and use the %s qualifier in the format string. Moreover, since this is a polymorphic type, I would have to create an indirect function that can handle an instance of any type of 'a .

My question is: why is OCaml missing this convenient specifier? Is it because there is no incentive to implement it? Is this due to the fact that some of them do not have a scammer under the hood, which is only in F #?

+7
f # ocaml
source share
2 answers

I would say that the β€œlack of fraud under the hood” is probably the reason.

In F #, %A specifier defers printing to the printer based on reflection β€” it uses run-time information to move and print the value. The reflection API used in this process is very specific to .NET. In addition, while comfortable, it is also a relatively expensive mechanism - it should not be used as a blanket specifier if you can use a more specific one.

From what I know, OCaml does not have the appropriate reflection capabilities that can be used here. There may be another mechanism that would allow you to do typical printing, but I'm not familiar enough with the internal components of OCaml.

+7
source share

The usual way to do this in OCaml is to use the %a specifier and write (or output) the printer for result to pass it.

It might look like this:

 type 'a result = | Success of 'a | Failure [@@deriving show] Format.printf "%a" (pp_result Format.pp_print_string) (Success "hello") 

where pp_result was generated by the deriving clause. Note that pp_result accepts the formatting function as an argument, which is used to print any 'a .

OCaml completely erases types (almost) at compile time, so reflection cannot be used to implement automatic printing, as in F #. It is not clear that reflection will work well in a language with abstract types. Anyway.

+6
source share

All Articles