2
votes

Can you explain why one works but not the other?

Given

//fu : unit -> unit
let fu() = ();;

This works

//exec : (unit -> unit) -> int -> unit
let exec (f:(unit -> unit)) (data:int) = f();;

//this works, and p : int -> unit
let p = exec fu;;

And it works for other types of data such as string, long, etc.

This doesn't work

//exec : (unit -> unit) -> obj -> unit
let exec (f:(unit -> unit)) (data:obj) = f();;

let p = exec fu;;

and I get the following error:

error FS0030: Value restriction. The value 'p' has been inferred to have generic type val p : ('_a -> unit)
Either make the arguments to 'p' explicit or, if you do not intend for it to be generic, add a type annotation.

Notice the only difference between these cases is the type of the data parameter. When it is obj or System.Object or 'a - it doesn't work.

Another thing is that if data has type obj then the following happens:

//Data type is obj
let exec (f:(unit -> unit)) (data:obj) = f();;

//specifying parameters explicitly
let p x = exec fu x;;

Now p has the signature of 'a -> unit, not obj -> unit.

So the question is: why the "shortcuted" currying doesn't work when data is obj or 'a and why the type of p is 'a -> unit when data was obj?

1

1 Answers

3
votes

So I think the problem is that F# appears to be generalizing at the wrong point (from your point of view):

Here is a version of your code that at first glance shouldn't typecheck:

let exec (f:unit -> unit)  (data:obj) = f();;
let p:int -> unit = exec (fun () -> ());;

This seems weird as int <> obj.

Also, here is an even simpler example which shows your behaviour (from the spec with modifications)

type Base() =
    member b.X = 1
type Derived(i : int) =
    inherit Base()
    member d.Y = i
let exec (f:unit -> unit)  (data:Base) = f();;
let p = exec (fun () -> ());;

which produces a value restriction error.

This makes it more clear that as F# inserts an implicit upcast before the function calls, the code is valid where it is a function, but once you make it an explicit value, this cast can't be used.

If you want your code to compile, you need to move the location of the upcast by adding a type annotation:

let exec (f:unit -> unit)  (data:obj) = f()
let p:obj -> unit = exec (fun () -> ());;