SML 中作为返回值和值限制的多态函数
基本上,我想要一个函数来返回多态函数,如下所示:
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于技术原因,不允许您泛化(即多态)函数调用的结果。调用的结果必须具有单态类型。如果不是这种情况,您可以通过以下肮脏的技巧破坏类型系统:
ref []
并返回forall 'a 类型的列表。 'a list ref
,就可以了:您现在正在将任意字符串的内容作为代码执行。不好。
通过坚持
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:
ref []
and get back a list of typeforall 'a . 'a list ref
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.