SML 如何检查变量类型?

标签 sml

有没有办法检查/测试变量的类型?

我想像这样使用它:

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/

相关文章:

sml - 在 SML 中解析具有多种数据类型的元组列表

带有 sml 模式的 emacs

sml - SML中的SOME和NONE选项有哪些?

sml - Poly/ML 中的共享库

types - 运算符操作数类型不匹配

compiler-errors - SML 错误 : syntax error: inserting DOT

module - 透明签名归属的惊人行为

list - number_in_month 练习(SML 列表迭代)

sml - SML 中的 If Else 中的多个语句

haskell - 好的类型系统可以区分不同基数的矩阵吗?