开发者

Polymorphic function as return value and value restriction in SML

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 r开发者_如何转开发eturns 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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜