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

**URL:** <https://discuss.ocaml.org/t/can-this-function-be-written-x-a-unit-a/6508>\
**Category:** Learning\
**Created:** [September 26, 2020, 9:41am UTC](https://discuss.ocaml.org/t/can-this-function-be-written-x-a-unit-a/6508 "2020-09-26T09:41:32Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![orbitz](https://sea2.discourse-cdn.com/flex020/user_avatar/discuss.ocaml.org/orbitz/32/110_2.png) [@orbitz](https://discuss.ocaml.org/u/orbitz)\
**Post date:** [September 26, 2020, 9:41am UTC](https://discuss.ocaml.org/t/can-this-function-be-written-x-a-unit-a/6508/1 "2020-09-26T09:41:32Z")

</div>

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

```auto
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

---

<div class="post-metadata">

**Author:** ![CraigFe](https://sea2.discourse-cdn.com/flex020/user_avatar/discuss.ocaml.org/craigfe/32/1989_2.png) [@CraigFe](https://discuss.ocaml.org/u/CraigFe)\
**Post date:** [September 26, 2020, 9:59am UTC](https://discuss.ocaml.org/t/can-this-function-be-written-x-a-unit-a/6508/2 "2020-09-26T09:59:18Z")

</div>

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

```ocaml
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?

---

<div class="post-metadata">

**Author:** ![gasche](https://sea2.discourse-cdn.com/flex020/user_avatar/discuss.ocaml.org/gasche/32/4_2.png) [@gasche](https://discuss.ocaml.org/u/gasche)\
**Post date:** [September 26, 2020, 11:33am UTC](https://discuss.ocaml.org/t/can-this-function-be-written-x-a-unit-a/6508/3 "2020-09-26T11:33:26Z")

</div>

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.
