Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there some way to get a value's type like c# or java's reflection in OCaml?

I use vscode+merlin to read OCaml code. Sometimes it can give me a type, but sometimes it only tell me that a type 'a, which is the same as telling me nothing. I have to guess a value's type by reading the code. Reading the code to conclude a value's type is important, but sometimes I doult if my guess is right.

So I want a method that can get the value's type at runtime, like reflection in Java or C#.

var a = 1;
Console.WriteLine(a.GetType());

Is there some way to do the same thing in OCaml?

like image 598
wang kai Avatar asked Nov 02 '25 17:11

wang kai


1 Answers

OCaml is statically typed. That is, its types exist only at compile time. At runtime there are only values. So you can't realistically have a function that determines the type of a value.

(IMHO there are real advantages to having types nailed down at compile time, and not allowing a program's behavior to depend on testing types at runtime. In general it makes programs clearer and easier to reason about.)

If you want to verify your guesses about types, you can do it at compile time by ascribing a type to a variable (or really to any expression).

For example you can say:

let (x : int list) = funtion_to_call arg1 arg2 in
. . .

If function_to_call returns something other than a list of ints, the compiler will issue an error at this point.

like image 125
Jeffrey Scofield Avatar answered Nov 04 '25 11:11

Jeffrey Scofield