Why ref raise has a weak type?

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

Why would you expect it to have a polymorphic type?

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

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

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:

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:

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
6 Likes