Is there any way to check/test the type of a variable?
I want to use it like this:
if x = int then foo
else if x = real then bar
else if x = string then
It's not possible to do what you want in general, even if x
is of polymorphic type (without doing the wrapping yourself as Chuck suggests).
This is a deliberate design decision; it makes it possible to make very strong conclusions about functions, just based on their types, that you couldn't make otherwise. For instance, it lets you say that a function with type 'a -> 'a
must be the identity function (or a function that always throws an exception, or a function that never returns). If you could inspect what 'a
was at runtime, you could write a sneaky program like
fun sneaky (x : 'a) : 'a = if x = int then infinite_loop() else x
that would violate the rule. (This is a pretty trivial example, but there are lots of less-trivial things you can do by knowing your type system has this property.)