Polymorphic function as return value and value limitation in SML

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

fun foo () = fn x => x

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

val foo = fn: unit → 'a →' a

but as soon as I actually call the foo function, the return value does not match the expected

val it = fn:?. X1 →? .X2

Impossible to generalize due to limitation of the meaning he says, any help? thanks in advance

+4
source share
1 answer

For technical reasons, you are not allowed to summarize (i.e. make polymorphic) the results of a function call. The result of the call must be of a monomorphic type. If this were not the case, you could undermine the type system with the following trick:

  • Call ref [] and return the list of types forall 'a . 'a list ref forall 'a . 'a list ref
  • Insert a line.
  • Delete function

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

By asserting that the value returned by ref [] is monomorphic, you will see 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.

+4
source

Source: https://habr.com/ru/post/1299589/


All Articles