# Why ref raise has a weak type?

**URL:** <https://discuss.ocaml.org/t/why-ref-raise-has-a-weak-type/16829>\
**Category:** Learning\
**Created:** [June 17, 2025, 7:27am UTC](https://discuss.ocaml.org/t/why-ref-raise-has-a-weak-type/16829 "2025-06-17T07:27:15Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![v01dXYZ](https://sea2.discourse-cdn.com/flex020/user_avatar/discuss.ocaml.org/v01dxyz/32/5993_2.png) [@v01dXYZ](https://discuss.ocaml.org/u/v01dXYZ)\
**Post date:** [June 17, 2025, 7:27am UTC](https://discuss.ocaml.org/t/why-ref-raise-has-a-weak-type/16829/1 "2025-06-17T07:27:15Z")

</div>

I don’t understand why ref raise has a weak type instead of a polymorphic type.

---

<div class="post-metadata">

**Author:** ![yallop](https://sea2.discourse-cdn.com/flex020/user_avatar/discuss.ocaml.org/yallop/32/517_2.png) [@yallop](https://discuss.ocaml.org/u/yallop)\
**Post date:** [June 17, 2025, 8:03am UTC](https://discuss.ocaml.org/t/why-ref-raise-has-a-weak-type/16829/2 "2025-06-17T08:03:13Z")

</div>

Why would you expect it to have a polymorphic type?

---

<div class="post-metadata">

**Author:** ![v01dXYZ](https://sea2.discourse-cdn.com/flex020/user_avatar/discuss.ocaml.org/v01dxyz/32/5993_2.png) [@v01dXYZ](https://discuss.ocaml.org/u/v01dXYZ)\
**Post date:** [June 17, 2025, 8:12am UTC](https://discuss.ocaml.org/t/why-ref-raise-has-a-weak-type/16829/3 "2025-06-17T08:12:34Z")

</div>

In case I’d like to provide a customable exception raiser. More broadly, why does ref remove polymorphism in function signatures ?

---

<div class="post-metadata">

**Author:** ![yallop](https://sea2.discourse-cdn.com/flex020/user_avatar/discuss.ocaml.org/yallop/32/517_2.png) [@yallop](https://discuss.ocaml.org/u/yallop)\
**Post date:** [June 17, 2025, 8:34am UTC](https://discuss.ocaml.org/t/why-ref-raise-has-a-weak-type/16829/4 "2025-06-17T08:34:09Z")

</div>

I see. It would be unsafe to allow programs like this:

```ocaml
let raiser : 'a. (unit -> 'a) ref = ref (fun () -> raise Not_found)

```

because the combination of the polymorphic type and the reference would make it possible to write to the reference at one type, and then read from it at another:

```ocaml
raiser := (fun () -> "a string")

(!raiser ()) + 1

```

However, what you want to do (only assigning functions that always raise exceptions to `raiser`) is safe, and you can achieve it by making `raiser` a reference to a polymorphic function rather than a polymorphic reference to a function:

```ocaml
type raiser = { fail: 'a. unit -> 'a }

let raise_not_found = { fail = fun () -> raise Not_found }
let raise_failure = { fail = fun () -> raise (Failure "failed") }

let raiser = ref raise_not_found
...
raiser := raise_failure

```
