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
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.