SML 如何检查变量类型?
有什么方法可以检查/测试变量的类型吗?
我想这样使用它:
if x = int then foo
else if x = real then bar
else if x = string then ...
else .....
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 .....
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
ML 语言是静态类型的,因此某个东西不可能在不同时间具有不同的类型。
x
有时不能具有int
类型,而有时又具有string
类型。如果您需要这样的行为,通常的方法是将值包装在编码类型信息的容器中,例如:然后您可以在构造函数上进行模式匹配:
在本例中,
x
明确地输入为wrapper
,因此可以工作。ML languages are statically typed, so it's not possible for something to have different types at different times.
x
can't sometimes have typeint
and at other times have the typestring
. 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:Then you can pattern-match on the constructor:
In this case,
x
is clearly typed as awrapper
, so that will work.即使
x
是多态类型(无需像 Chuck 建议的那样自行包装),一般情况下也不可能做您想做的事情。这是一个经过深思熟虑的设计决定;它使得仅根据函数的类型就可以对函数做出非常有力的结论,而这是其他方式无法得出的。例如,它可以让您说一个类型为
'a ->; 的函数。 'a
必须是恒等函数(或者总是抛出异常的函数,或者从不返回的函数)。如果您可以在运行时检查'a
的内容,您就可以编写一个像这样违反规则的偷偷摸摸的程序。 (这是一个非常简单的示例,但是通过了解您的类型系统具有此属性,您可以做很多不那么简单的事情。)
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 likethat 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.)