3 ms·
Can you expand on this point? When I tried OCaml a little time ago, it was a pain even to have a polymorphic print function. I would be surprised if there was a
by pathsjs 11y ago
Can you expand on this point? When I tried OCaml a little time ago, it was a pain even to have a polymorphic print function. I would be surprised if there was a serialization mechanism that produces a binary form that cannot be adapted to produce a textual form
- rbehrends 11y agoHave a look at the Marshal module. Marshal can be polymorphic because it has compiler support and can rely on runtime internals (similar to how comparison is polymorphic or the Printf module can work). It works for pretty much everything where the representation is known to OCaml (the exceptions are things like extern C types wrapped in OCaml types). Example: let f x = 2 * x + 1 let s = Marshal.to_string f [ Marshal.Closures ] let g: (int -> int) = Marshal.from_string s 0 let () = Printf.printf "%d\n" (g 2) Note: this may not work in the REPL and you may have to put it in a file and compile it. Note also that serialization need not be polymorphic. See e.g. the s-expression mechanism [2], which relies on metaprogramming facilities. [1] http://caml.inria.fr/pub/docs/manual-ocaml/libref/Marshal.html http://caml.inria.fr/pub/docs/manual-ocaml/libref/Marshal.ht... [2] https://realworldocaml.org/v1/en/html/data-serialization-with-s-expressions.html https://realworldocaml.org/v1/en/html/data-serialization-wit...
- pathsjs 11y agoThank you. s-exps are a pain, because you have to manually specify the function sexp_of_t for any type t that you want to support
- rbehrends 11y agoNo, that's what the ppx rewriter is for (the metaprogramming I mentioned). You write type foo = ... with sexp and those functions will be generated automatically for you. Mind you, the whole Jane Street Core machinery is still a bit heavyweight for my taste, but that particular concern shouldn't be an issue. For example, in utop: utop # #require "core";; utop # #require "core.syntax";; utop # open Core.Std;; utop # type foo = int * string with sexp;; type foo = int * string val foo_of_sexp : Sexp.t -> foo = <fun> val sexp_of_foo : foo -> Sexp.t = <fun> utop # sexp_of_foo (1, "foo");; - : Sexp.t = (1 foo)