有没有办法检查/测试变量的类型?
我想像这样使用它:
if x = int then foo
else if x = real then bar
else if x = string then ...
else .....
最佳答案
ML 语言是静态类型的,因此不可能在不同的时间有不同的类型。 x
有时不能有类型 int
其他时候类型为 string
.如果您需要这样的行为,通常的做法是将值包装在一个对类型信息进行编码的容器中,例如:
datatype wrapper = Int of int | Real of real | String of string
然后你可以在构造函数上进行模式匹配:
case x of Int x -> foo
| Real x -> bar
| String x -> ...
在这种情况下,
x
清楚地输入为 wrapper
,这样就可以了。
关于SML 如何检查变量类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3713948/