Debian Codegraph @

doc/guide/src/ValueRestriction.adoc

raw
1 = ValueRestriction
2 :toc:
3
4 The value restriction is a rule that governs when type inference is
5 allowed to polymorphically generalize a value declaration. In short,
6 the value restriction says that generalization can only occur if the
7 right-hand side of an expression is syntactically a value. For
8 example, in
9
10 [source,sml]
11 ----
12 val f = fn x => x
13 val _ = (f "foo"; f 13)
14 ----
15
16 the expression `fn x \=> x` is syntactically a value, so `f` has
17 polymorphic type `'a \-> 'a` and both calls to `f` type check. On the
18 other hand, in
19
20 [source,sml]
21 ----
22 val f = let in fn x => x end
23 val _ = (f "foo"; f 13)
24 ----
25
26 the expression `let in fn x \=> x end` is not syntactically a value
27 and so `f` can either have type `int \-> int` or `string \-> string`,
28 but not `'a \-> 'a`. Hence, the program does not type check.
29
30 <<DefinitionOfStandardML#,The Definition of Standard ML>> spells out
31 precisely which expressions are syntactic values (it refers to such
32 expressions as _non-expansive_). An expression is a value if it is of
33 one of the following forms.
34
35 * a constant (`13`, `"foo"`, `13.0`, ...)
36 * a variable (`x`, `y`, ...)
37 * a function (`fn x \=> e`)
38 * the application of a constructor other than `ref` to a value (`Foo v`)
39 * a type constrained value (`v: t`)
40 * a tuple in which each field is a value `(v1, v2, ...)`
41 * a record in which each field is a value `{l1 = v1, l2 = v2, ...}`
42 * a list in which each element is a value `[v1, v2, ...]`
43
44
45 == Why the value restriction exists
46
47 The value restriction prevents a ref cell (or an array) from holding
48 values of different types, which would allow a value of one type to be
49 cast to another and hence would break type safety. If the restriction
50 were not in place, the following program would type check.
51
52 [source,sml]
53 ----
54 val r: 'a option ref = ref NONE
55 val r1: string option ref = r
56 val r2: int option ref = r
57 val () = r1 := SOME "foo"
58 val v: int = valOf (!r2)
59 ----
60
61 The first line violates the value restriction because `ref NONE` is
62 not a value. All other lines are type correct. By its last line, the
63 program has cast the string `"foo"` to an integer. This breaks type
64 safety, because now we can add a string to an integer with an
65 expression like `v + 13`. We could even be more devious, by adding
66 the following two lines, which allow us to treat the string `"foo"`
67 as a function.
68
69 [source,sml]
70 ----
71 val r3: (int -> int) option ref = r
72 val v: int -> int = valOf (!r3)
73 ----
74
75 Eliminating the explicit `ref` does nothing to fix the problem. For
76 example, we could replace the declaration of `r` with the following.
77
78 [source,sml]
79 ----
80 val f: unit -> 'a option ref = fn () => ref NONE
81 val r: 'a option ref = f ()
82 ----
83
84 The declaration of `f` is well typed, while the declaration of `r`
85 violates the value restriction because `f ()` is not a value.
86
87
88 == Unnecessarily rejected programs
89
90 Unfortunately, the value restriction rejects some programs that could
91 be accepted.
92
93 [source,sml]
94 ----
95 val id: 'a -> 'a = fn x => x
96 val f: 'a -> 'a = id id
97 ----
98
99 The type constraint on `f` requires `f` to be polymorphic, which is
100 disallowed because `id id` is not a value. MLton reports the
101 following type error.
102
103 ----
104 Error: z.sml 2.5-2.5.
105 Type of variable cannot be generalized in expansive declaration: f.
106 type: ['a] -> ['a]
107 in: val 'a f: ('a -> 'a) = id id
108 ----
109
110 MLton indicates the inability to make `f` polymorphic by saying that
111 the type of `f` cannot be generalized (made polymorphic) its
112 declaration is expansive (not a value). MLton doesn't explicitly
113 mention the value restriction, but that is the reason. If we leave
114 the type constraint off of `f`
115
116 [source,sml]
117 ----
118 val id: 'a -> 'a = fn x => x
119 val f = id id
120 ----
121
122 then the program succeeds; however, MLton gives us the following
123 warning.
124
125 ----
126 Warning: z.sml 2.5-2.5.
127 Type of variable was not inferred and could not be generalized: f.
128 type: ??? -> ???
129 in: val f = id id
130 ----
131
132 This warning indicates that MLton couldn't polymorphically generalize
133 `f`, nor was there enough context using `f` to determine its type.
134 This in itself is not a type error, but it it is a hint that something
135 is wrong with our program. Using `f` provides enough context to
136 eliminate the warning.
137
138 [source,sml]
139 ----
140 val id: 'a -> 'a = fn x => x
141 val f = id id
142 val _ = f 13
143 ----
144
145 But attempting to use `f` as a polymorphic function will fail.
146
147 [source,sml]
148 ----
149 val id: 'a -> 'a = fn x => x
150 val f = id id
151 val _ = f 13
152 val _ = f "foo"
153 ----
154
155 ----
156 Error: z.sml 4.9-4.15.
157 Function applied to incorrect argument.
158 expects: [int]
159 but got: [string]
160 in: f "foo"
161 ----
162
163
164 == Alternatives to the value restriction
165
166 There would be nothing wrong with treating `f` as polymorphic in
167
168 [source,sml]
169 ----
170 val id: 'a -> 'a = fn x => x
171 val f = id id
172 ----
173
174 One might think that the value restriction could be relaxed, and that
175 only types involving `ref` should be disallowed. Unfortunately, the
176 following example shows that even the type `'a \-> 'a` can cause
177 problems. If this program were allowed, then we could cast an integer
178 to a string (or any other type).
179
180 [source,sml]
181 ----
182 val f: 'a -> 'a =
183 let
184 val r: 'a option ref = ref NONE
185 in
186 fn x =>
187 let
188 val y = !r
189 val () = r := SOME x
190 in
191 case y of
192 NONE => x
193 | SOME y => y
194 end
195 end
196 val _ = f 13
197 val _ = f "foo"
198 ----
199
200 The previous version of Standard ML took a different approach
201 (<<References#MilnerEtAl90,MilnerEtAl90>>, <<References#Tofte90,Tofte90>>, <<ImperativeTypeVariable#>>)
202 than the value restriction. It encoded information in the type system
203 about when ref cells would be created, and used this to prevent a ref
204 cell from holding multiple types. Although it allowed more programs
205 to be type checked, this approach had significant drawbacks. First,
206 it was significantly more complex, both for implementers and for
207 programmers. Second, it had an unfortunate interaction with the
208 modularity, because information about ref usage was exposed in module
209 signatures. This either prevented the use of references for
210 implementing a signature, or required information that one would like
211 to keep hidden to propagate across modules.
212
213 In the early nineties, Andrew Wright studied about 250,000 lines of
214 existing SML code and discovered that it did not make significant use
215 of the extended typing ability, and proposed the value restriction as
216 a simpler alternative (<<References#Wright95,Wright95>>). This was adopted in the
217 revised <<DefinitionOfStandardML#,Definition>>.
218
219
220 == Working with the value restriction
221
222 One technique that works with the value restriction is
223 <<EtaExpansion#>>. We can use eta expansion to make our `id id`
224 example type check follows.
225
226 [source,sml]
227 ----
228 val id: 'a -> 'a = fn x => x
229 val f: 'a -> 'a = fn z => (id id) z
230 ----
231
232 This solution means that the computation (in this case `id id`) will
233 be performed each time `f` is applied, instead of just once when `f`
234 is declared. In this case, that is not a problem, but it could be if
235 the declaration of `f` performs substantial computation or creates a
236 shared data structure.
237
238 Another technique that sometimes works is to move a monomorphic
239 computation prior to a (would-be) polymorphic declaration so that the
240 expression is a value. Consider the following program, which fails
241 due to the value restriction.
242
243 [source,sml]
244 ----
245 datatype 'a t = A of string | B of 'a
246 val x: 'a t = A (if true then "yes" else "no")
247 ----
248
249 It is easy to rewrite this program as
250
251 [source,sml]
252 ----
253 datatype 'a t = A of string | B of 'a
254 local
255 val s = if true then "yes" else "no"
256 in
257 val x: 'a t = A s
258 end
259 ----
260
261 The following example (taken from <<References#Wright95,Wright95>>) creates a ref
262 cell to count the number of times a function is called.
263
264 [source,sml]
265 ----
266 val count: ('a -> 'a) -> ('a -> 'a) * (unit -> int) =
267 fn f =>
268 let
269 val r = ref 0
270 in
271 (fn x => (r := 1 + !r; f x), fn () => !r)
272 end
273 val id: 'a -> 'a = fn x => x
274 val (countId: 'a -> 'a, numCalls) = count id
275 ----
276
277 The example does not type check, due to the value restriction.
278 However, it is easy to rewrite the program, staging the ref cell
279 creation before the polymorphic code.
280
281 [source,sml]
282 ----
283 datatype t = T of int ref
284 val count1: unit -> t = fn () => T (ref 0)
285 val count2: t * ('a -> 'a) -> (unit -> int) * ('a -> 'a) =
286 fn (T r, f) => (fn () => !r, fn x => (r := 1 + !r; f x))
287 val id: 'a -> 'a = fn x => x
288 val t = count1 ()
289 val countId: 'a -> 'a = fn z => #2 (count2 (t, id)) z
290 val numCalls = #1 (count2 (t, id))
291 ----
292
293 Of course, one can hide the constructor `T` inside a `local` or behind
294 a signature.
295
296
297 == Also see
298
299 * <<ImperativeTypeVariable#>>