Debian Codegraph @

doc/guide/src/DefineTypeBeforeUse.adoc

raw
1 = DefineTypeBeforeUse
2
3 <<StandardML#,Standard ML>> requires types to be defined before they are
4 used. Because of type inference, the use of a type can be implicit;
5 hence, this requirement is more subtle than it might appear. For
6 example, the following program is not type correct, because the type
7 of `r` is `t option ref`, but `t` is defined after `r`.
8
9 [source,sml]
10 ----
11 val r = ref NONE
12 datatype t = A | B
13 val () = r := SOME A
14 ----
15
16 MLton reports the following error, indicating that the type defined on
17 line 2 is used on line 1.
18
19 ----
20 Error: z.sml 3.10-3.20.
21 Function applied to incorrect argument.
22 expects: _ * [???] option
23 but got: _ * [t] option
24 in: := (r, SOME A)
25 note: type would escape its scope: t
26 escape from: z.sml 2.10-2.10
27 escape to: z.sml 1.1-1.16
28 Warning: z.sml 1.5-1.5.
29 Type of variable was not inferred and could not be generalized: r.
30 type: ??? option ref
31 in: val r = ref NONE
32 ----
33
34 While the above example is benign, the following example shows how to
35 cast an integer to a function by (implicitly) using a type before it
36 is defined. In the example, the ref cell `r` is of type
37 `t option ref`, where `t` is defined _after_ `r`, as a parameter to
38 functor `F`.
39
40 [source,sml]
41 ----
42 val r = ref NONE
43 functor F (type t
44 val x: t) =
45 struct
46 val () = r := SOME x
47 fun get () = valOf (!r)
48 end
49 structure S1 = F (type t = unit -> unit
50 val x = fn () => ())
51 structure S2 = F (type t = int
52 val x = 13)
53 val () = S1.get () ()
54 ----
55
56 MLton reports the following error.
57
58 ----
59 Warning: z.sml 1.5-1.5.
60 Type of variable was not inferred and could not be generalized: r.
61 type: ??? option ref
62 in: val r = ref NONE
63 Error: z.sml 5.16-5.26.
64 Function applied to incorrect argument.
65 expects: _ * [???] option
66 but got: _ * [t] option
67 in: := (r, SOME x)
68 note: type would escape its scope: t
69 escape from: z.sml 2.17-2.17
70 escape to: z.sml 1.1-1.16
71 Warning: z.sml 6.11-6.13.
72 Type of variable was not inferred and could not be generalized: get.
73 type: unit -> ???
74 in: fun get () = (valOf (! r))
75 Error: z.sml 12.10-12.18.
76 Function not of arrow type.
77 function: [unit]
78 in: (S1.get ()) ()
79 ----