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 ...
else .....
ML languages are statically typed, so it's not possible for something to have different types at different times. x
can't sometimes have type int
and at other times have the type string
. If you need behavior like this, the normal way to go about it is to wrap the value in a container that encodes type information, like:
datatype wrapper = Int of int | Real of real | String of string
Then you can pattern-match on the constructor:
case x of Int x -> foo
| Real x -> bar
| String x -> ...
In this case, x
is clearly typed as a wrapper
, so that will work.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With