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 .....
Run Code Online (Sandbox Code Playgroud)
Chu*_*uck 21
ML语言是静态类型的,因此某些东西在不同时间不可能有不同的类型.x
有时不能有类型int
,有时也有类型string
.如果你需要这样的行为,通常的方法是将值包装在一个编码类型信息的容器中,如:
datatype wrapper = Int of int | Real of real | String of string
Run Code Online (Sandbox Code Playgroud)
然后你可以在构造函数上进行模式匹配:
case x of Int x -> foo
| Real x -> bar
| String x -> ...
Run Code Online (Sandbox Code Playgroud)
在这种情况下,x
显然键入为a wrapper
,这样就可以了.
即使x
是多态类型也不可能做你想要的一般事情(没有像Chuck建议的那样自己做包装).
这是一个刻意的设计决定; 它使得有可能就功能做出非常有力的结论,只是根据它们的类型,你无法做到.例如,它允许您说具有类型的函数'a -> 'a
必须是标识函数(或始终抛出异常的函数,或者永远不会返回的函数).如果你可以检查'a
运行时的内容,你可以写一个偷偷摸摸的程序,比如
fun sneaky (x : 'a) : 'a = if x = int then infinite_loop() else x
Run Code Online (Sandbox Code Playgroud)
这将违反规则.(这是一个非常简单的例子,但是你知道你的类型系统有这个属性,你可以做很多不那么重要的事情.)