Question

I learned that functions accepting arbitrary types could be created, like these:

let f x = x;;

let f x = ();;

let f (x : 'a) = ();;

But I could not find a way to utilize type information inside function, like this:

let print_is = function
    | (x : int) -> print_int x
    | (s : string) -> print_string s
    | _ -> print_string "***";;

Is it really impossible at all, and if so - what is the underlying idea of such restriction? Or I just failed to google properly?

Was it helpful?

Solution

OCaml does not keep type information at run-time: in order to write the program you suggest, one would need to match on the type of x, thus one would need a value that represents the type of x in order to pattern-match on it.

I see two ways to further reply to your question:

  • inspecting the type of a parameter and building a value that represents the said type is a research problem that is still actively investigated: it is hard to perform these operations in a type-safe way that furthermore does not break abstraction. Grégoire Henry is currently doing that and seems to be sharing his work on https://github.com/c-cube/ocaml-ty
  • If you're looking for a way to print an arbitrary value, the natural way in OCaml would be to directly use the "right" function to print the type you want, as there is no universal printer in OCaml. That being said, there are extra libraries such as deriving that can generate automatic printers for your type definitions.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top