SML How to check variable type?

此生再无相见时 提交于 2019-12-05 19:52:36

问题


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

回答1:


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.




回答2:


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 like

fun sneaky (x : 'a) : 'a = if x = int then infinite_loop() else x

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



来源:https://stackoverflow.com/questions/3713948/sml-how-to-check-variable-type

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!