Chetna Shah
Chetna Shah

Reputation: 67

Why is `ref None` value restricted in Ocaml?

The value restriction rule says that generalization can only occur if the right-hand side of an expression is syntactically a value.

I don't understand why let r = ref None is value restricted? How come ref (Some 2) is a value and ref None is not?

Is it the case that None is like a type constructor? None is not a value? It seems to me that None is a polymorphic value. Is there any such thing as polymorphic value?

It seems to me that value restriction occurs when there is some sort of interaction with multiple polymorphic entities like id id or ref None.

I am a beginner to OCaml doing self study. Any help is appreciated.

Upvotes: 3

Views: 304

Answers (2)

Andreas Rossberg
Andreas Rossberg

Reputation: 36088

Mutable state must not be polymorphic. The ref case is the reason why the value restriction exists in the first place. Consider:

let r = ref None in     (* consider this was r : 'a option ref *)
r := Some "boo";        (* then this would be well-typed *)
unSome (!r) + 1         (* and this would be well-typed as well -- BOOM! *)

where unSome is a helper:

let unSome = function Some x -> x | None -> raise Not_found

Upvotes: 6

Jeffrey Scofield
Jeffrey Scofield

Reputation: 66818

Neither ref None nor ref (Some 2) is a value in the sense used for the value restriction. Both of them are applications of the function ref.

It doesn't make sense to talk about generalizing ref (Some 2) as there is no possible polymorphism.

None is a value but ref None is not a value (in the syntactic sense used for the value restriction). Since None is a value it can be generalized (so it's polymorphic):

# let my_none = None;;
val my_none : 'a option = None

# let f x = if x then Some 3 else my_none;;
val f : bool -> int option = <fun>
# let g x = if x then Some "abc" else my_none;;
val g : bool -> string option = <fun>

Since my_none is polymorphic it can function as a value of type int option and also as a value of type string option.

Update

OCaml has a "relaxed" value restriction whereby some things that are not syntactic values can still be generalized (made polymorphic).

You can read about the relaxed value restriction in this paper, which I often cite. (I also reread it periodically because I tend to forget the argument over time.)

Jacques Garrigue, Relaxing the Value Restriction

Upvotes: 4

Related Questions