SML 如何检查变量类型?

发布于 2024-09-24 02:57:17 字数 159 浏览 1 评论 0原文

有什么方法可以检查/测试变量的类型吗?

我想这样使用它:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

国粹 2024-10-01 02:57:17

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,因此可以工作。

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.

夜访吸血鬼 2024-10-01 02:57:17

即使 x 是多态类型(无需像 Chuck 建议的那样自行包装),一般情况下也不可能做您想做的事情。

这是一个经过深思熟虑的设计决定;它使得仅根据函数的类型就可以对函数做出非常有力的结论,而这是其他方式无法得出的。例如,它可以让您说一个类型为 'a ->; 的函数。 'a 必须是恒等函数(或者总是抛出异常的函数,或者从不返回的函数)。如果您可以在运行时检查 'a 的内容,您就可以编写一个像

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

这样违反规则的偷偷摸摸的程序。 (这是一个非常简单的示例,但是通过了解您的类型系统具有此属性,您可以做很多不那么简单的事情。)

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文