SML 中作为返回值和值限制的多态函数

发布于 2024-08-19 08:57:51 字数 281 浏览 2 评论 0原文

基本上,我想要一个函数来返回多态函数,如下所示:

fun foo () = fn x => x

所以 foo 函数接受一个类型为 unit 的值并返回一个多态恒等函数 编译器对此很满意,它给了我:

val foo = fn : unit -> '一-> 'a

但是一旦我实际调用 foo 函数,返回值就不是我所期望的

val it = fn : ?.X1 -> ?.X2

由于它所说的值限制而无法概括,有什么帮助吗?提前致谢

Basically, I want to have a function to return a polymorphic function, some thing like this:

fun foo () = fn x => x

So the foo function takes in a value of type unit and returns a polymorphic identity function
and the compiler is happy with that, it gives me:

val foo = fn : unit -> 'a -> 'a

but once I actually call the foo function, the return value is not what I expected

val it = fn : ?.X1 -> ?.X2

Can't generalize because of value restriction it says, any help? thanks in advance

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

不顾 2024-08-26 08:57:51

由于技术原因,不允许您泛化(即多态)函数调用的结果。调用的结果必须具有单态类型。如果不是这种情况,您可以通过以下肮脏的技巧破坏类型系统:

  1. 调用 ref [] 并返回 forall 'a 类型的列表。 'a list ref
  2. 插入一个字符串。
  3. 删除一个函数

,就可以了:您现在正在将任意字符串的内容作为代码执行。不好。

通过坚持 ref [] 返回的值是单态的,可以确保它可以用作字符串列表或函数列表,但不能同时用作两者。所以这是我们为类型安全付出的代价的一部分。

For technical reasons, you are not allowed to generalize (i.e., make polymorphic) the results of a function call. The result of a call must have a monomorphic type. If this weren't the case, you could subvert the type system by the following dirty trick:

  1. Call ref [] and get back a list of type forall 'a . 'a list ref
  2. Insert a string.
  3. Remove a function

and there you are: you are now executing the contents of an arbitrary string as code. Not Good.

By insisting that the value returned by ref [] be monomorphic, you ensure that it can be used as a list of strings or a list of functions but not both. So this is part of the price we pay for type safety.

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