Can this function be written? ?x:'a -> unit -> 'a

Is it possible to write a function that the optional parameter has a type variable AND a default value? For example:

let f : type t. ?x:t -> unit -> t = fun ?(x=10) () -> x;;

Line 1, characters 44-46:
Error: This expression has type int but an expression was expected of type t

Provided that the default behaviour is either “raising an exception” or “not terminating”, the answer is yes. Otherwise, such a definition requires magic.

let rec spin x = spin x

let f : 'a. ?x:'a -> unit -> 'a = fun ?(x = assert false) () -> x
let f : 'a. ?x:'a -> unit -> 'a = fun ?(x = spin ()) () -> x
let f : 'a. ?x:'a -> unit -> 'a = fun ?(x = Obj.magic ()) () -> x

What default value would be compatible with every type parameter?

1 Like

We could have a function where the default value is at a specific instance of the polymorphic function type; you would get the specific instance when the parameter is missing, but still be able to instantiate in other ways when passing an explicit parameter.

However, this is not how optional-arguments are type-checked in OCaml, so you are not allowed to do what @orbitz wants.

1 Like