Debian Codegraph @

doc/guide/src/TypeIndexedValues.adoc

raw
1 = TypeIndexedValues
2
3 <<StandardML#,Standard ML>> does not support ad hoc polymorphism. This
4 presents a challenge to programmers. The problem is that at first
5 glance there seems to be no practical way to implement something like
6 a function for converting a value of any type to a string or a
7 function for computing a hash value for a value of any type.
8 Fortunately there are ways to implement type-indexed values in SML as
9 discussed in <<References#Yang98,Yang98>>. Various articles such as
10 <<References#Danvy98,Danvy98>>, <<References#Ramsey11,Ramsey11>>, <<References#Elsman04,Elsman04>>,
11 <<References#Kennedy04,Kennedy04>>, and <<References#Benton05,Benton05>> also contain examples of
12 type-indexed values.
13
14 *NOTE:* The technique used in the following example uses an early (and
15 somewhat broken) variation of the basic technique used in an
16 experimental generic programming library (see
17 https://github.com/MLton/mltonlib/blob/master/com/ssh/generic/unstable/README[`README`]) that can
18 be found from the MLton repository. The generic programming library
19 also includes a more advanced generic pretty printing function (see
20 https://github.com/MLton/mltonlib/blob/master/com/ssh/generic/unstable/public/value/pretty.sig[`pretty.sig`]).
21
22 == Example: Converting any SML value to (roughly) SML syntax
23
24 Consider the problem of converting any SML value to a textual
25 presentation that matches the syntax of SML as closely as possible.
26 One solution is a type-indexed function that maps a given type to a
27 function that maps any value (of the type) to its textual
28 presentation. A type-indexed function like this can be useful for a
29 variety of purposes. For example, one could use it to show debugging
30 information. We'll call this function `show`.
31
32 We'll do a fairly complete implementation of `show`. We do not
33 distinguish infix and nonfix constructors, but that is not an
34 intrinsic property of SML datatypes. We also don't reconstruct a type
35 name for the value, although it would be particularly useful for
36 functional values. To reconstruct type names, some changes would be
37 needed and the reader is encouraged to consider how to do that. A
38 more realistic implementation would use some pretty printing
39 combinators to compute a layout for the result. This should be a
40 relatively easy change (given a suitable pretty printing library).
41 Cyclic values (through references and arrays) do not have a standard
42 textual presentation and it is impossible to convert arbitrary
43 functional values (within SML) to a meaningful textual presentation.
44 Finally, it would also make sense to show sharing of references and
45 arrays. We'll leave these improvements to an actual library
46 implementation.
47
48 The following code uses the <<Fixpoints#,fixpoint framework>> and other
49 utilities from an Extended Basis library (see
50 https://github.com/MLton/mltonlib/blob/master/com/ssh/extended-basis/unstable/README[`README`]).
51
52 === Signature
53
54 Let's consider the design of the `SHOW` signature:
55 [source,sml]
56 ----
57 infixr -->
58
59 signature SHOW = sig
60 type 'a t (* complete type-index *)
61 type 'a s (* incomplete sum *)
62 type ('a, 'k) p (* incomplete product *)
63 type u (* tuple or unlabelled product *)
64 type l (* record or labelled product *)
65
66 val show : 'a t -> 'a -> string
67
68 (* user-defined types *)
69 val inj : ('a -> 'b) -> 'b t -> 'a t
70
71 (* tuples and records *)
72 val * : ('a, 'k) p * ('b, 'k) p -> (('a, 'b) product, 'k) p
73
74 val U : 'a t -> ('a, u) p
75 val L : string -> 'a t -> ('a, l) p
76
77 val tuple : ('a, u) p -> 'a t
78 val record : ('a, l) p -> 'a t
79
80 (* datatypes *)
81 val + : 'a s * 'b s -> (('a, 'b) sum) s
82
83 val C0 : string -> unit s
84 val C1 : string -> 'a t -> 'a s
85
86 val data : 'a s -> 'a t
87
88 val Y : 'a t Tie.t
89
90 (* exceptions *)
91 val exn : exn t
92 val regExn : (exn -> ('a * 'a s) option) -> unit
93
94 (* some built-in type constructors *)
95 val refc : 'a t -> 'a ref t
96 val array : 'a t -> 'a array t
97 val list : 'a t -> 'a list t
98 val vector : 'a t -> 'a vector t
99 val --> : 'a t * 'b t -> ('a -> 'b) t
100
101 (* some built-in base types *)
102 val string : string t
103 val unit : unit t
104 val bool : bool t
105 val char : char t
106 val int : int t
107 val word : word t
108 val real : real t
109 end
110 ----
111
112 While some details are shaped by the specific requirements of `show`,
113 there are a number of (design) patterns that translate to other
114 type-indexed values. The former kind of details are mostly shaped by
115 the syntax of SML values that `show` is designed to produce. To this
116 end, abstract types and phantom types are used to distinguish
117 incomplete record, tuple, and datatype type-indices from each other
118 and from complete type-indices. Also, names of record labels and
119 datatype constructors need to be provided by the user.
120
121 ==== Arbitrary user-defined datatypes
122
123 Perhaps the most important pattern is how the design supports
124 arbitrary user-defined datatypes. A number of combinators together
125 conspire to provide the functionality. First of all, to support new
126 user-defined types, a combinator taking a conversion function to a
127 previously supported type is provided:
128 [source,sml]
129 ----
130 val inj : ('a -> 'b) -> 'b t -> 'a t
131 ----
132
133 An injection function is sufficient in this case, but in the general
134 case, an embedding with injection and projection functions may be
135 needed.
136
137 To support products (tuples and records) a product combinator is
138 provided:
139 [source,sml]
140 ----
141 val * : ('a, 'k) p * ('b, 'k) p -> (('a, 'b) product, 'k) p
142 ----
143 The second (phantom) type variable `'k` is there to distinguish
144 between labelled and unlabelled products and the type `p`
145 distinguishes incomplete products from complete type-indices of type
146 `t`. Most type-indexed values do not need to make such distinctions.
147
148 To support sums (datatypes) a sum combinator is provided:
149 [source,sml]
150 ----
151 val + : 'a s * 'b s -> (('a, 'b) sum) s
152 ----
153 Again, the purpose of the type `s` is to distinguish incomplete sums
154 from complete type-indices of type `t`, which usually isn't necessary.
155
156 Finally, to support recursive datatypes, including sets of mutually
157 recursive datatypes, a <<Fixpoints#,fixpoint tier>> is provided:
158 [source,sml]
159 ----
160 val Y : 'a t Tie.t
161 ----
162
163 Together these combinators (with the more domain specific combinators
164 `U`, `L`, `tuple`, `record`, `C0`, `C1`, and `data`) enable one to
165 encode a type-index for any user-defined datatype.
166
167 ==== Exceptions
168
169 The `exn` type in SML is a <<UniversalType#,universal type>> into which
170 all types can be embedded. SML also allows a program to generate new
171 exception variants at run-time. Thus a mechanism is required to register
172 handlers for particular variants:
173 [source,sml]
174 ----
175 val exn : exn t
176 val regExn : (exn -> ('a * 'a s) option) -> unit
177 ----
178
179 The universal `exn` type-index then makes use of the registered
180 handlers. The above particular form of handler, which converts an
181 exception value to a value of some type and a type-index for that type
182 (essentially an existential type) is designed to make it convenient to
183 write handlers. To write a handler, one can conveniently reuse
184 existing type-indices:
185 [source,sml]
186 ----
187 exception Int of int
188
189 local
190 open Show
191 in
192 val () = regExn (fn Int v => SOME (v, C1"Int" int)
193 | _ => NONE)
194 end
195 ----
196
197 Note that a single handler may actually handle an arbitrary number of
198 different exceptions.
199
200 ==== Other types
201
202 Some built-in and standard types typically require special treatment
203 due to their special nature. The most important of these are arrays
204 and references, because cyclic data (ignoring closures) and observable
205 sharing can only be constructed through them.
206
207 When arrow types are really supported, unlike in this case, they
208 usually need special treatment due to the contravariance of arguments.
209
210 Lists and vectors require special treatment in the case of `show`,
211 because of their special syntax. This isn't usually the case.
212
213 The set of base types to support also needs to be considered unless
214 one exports an interface for constructing type-indices for entirely
215 new base types.
216
217 == Usage
218
219 Before going to the implementation, let's look at some examples. For
220 the following examples, we'll assume a structure binding
221 `Show :> SHOW`. If you want to try the examples immediately, just
222 skip forward to the implementation.
223
224 To use `show`, one first needs a type-index, which is then given to
225 `show`. To show a list of integers, one would use the type-index
226 `list int`, which has the type `int list Show.t`:
227 [source,sml]
228 ----
229 val "[3, 1, 4]" =
230 let open Show in show (list int) end
231 [3, 1, 4]
232 ----
233
234 Likewise, to show a list of lists of characters, one would use the
235 type-index `list (list char)`, which has the type `char list list
236 Show.t`:
237 [source,sml]
238 ----
239 val "[[#\"a\", #\"b\", #\"c\"], []]" =
240 let open Show in show (list (list char)) end
241 [[#"a", #"b", #"c"], []]
242 ----
243
244 Handling standard types is not particularly interesting. It is more
245 interesting to see how user-defined types can be handled. Although
246 the `option` datatype is a standard type, it requires no special
247 support, so we can treat it as a user-defined type. Options can be
248 encoded easily using a sum:
249 [source,sml]
250 ----
251 fun option t = let
252 open Show
253 in
254 inj (fn NONE => INL ()
255 | SOME v => INR v)
256 (data (C0"NONE" + C1"SOME" t))
257 end
258
259 val "SOME 5" =
260 let open Show in show (option int) end
261 (SOME 5)
262 ----
263
264 Readers new to type-indexed values might want to type annotate each
265 subexpression of the above example as an exercise. (Use a compiler to
266 check your annotations.)
267
268 Using a product, user specified records can be also be encoded easily:
269 [source,sml]
270 ----
271 val abc = let
272 open Show
273 in
274 inj (fn {a, b, c} => a & b & c)
275 (record (L"a" (option int) *
276 L"b" real *
277 L"c" bool))
278 end
279
280 val "{a = SOME 1, b = 3.0, c = false}"
281 let open Show in show abc end
282 {a = SOME 1, b = 3.0, c = false}
283 ----
284
285 As you can see, both of the above use `inj` to inject user-defined
286 types to the general purpose sum and product types.
287
288 Of particular interest is whether recursive datatypes and cyclic data
289 can be handled. For example, how does one write a type-index for a
290 recursive datatype such as a cyclic graph?
291 [source,sml]
292 ----
293 datatype 'a graph = VTX of 'a * 'a graph list ref
294 fun arcs (VTX (_, r)) = r
295 ----
296
297 Using the `Show` combinators, we could first write a new type-index
298 combinator for `graph`:
299 [source,sml]
300 ----
301 fun graph a = let
302 open Tie Show
303 in
304 fix Y (fn graph_a =>
305 inj (fn VTX (x, y) => x & y)
306 (data (C1"VTX"
307 (tuple (U a *
308 U (refc (list graph_a)))))))
309 end
310 ----
311
312 To show a graph with integer labels
313 [source,sml]
314 ----
315 val a_graph = let
316 val a = VTX (1, ref [])
317 val b = VTX (2, ref [])
318 val c = VTX (3, ref [])
319 val d = VTX (4, ref [])
320 val e = VTX (5, ref [])
321 val f = VTX (6, ref [])
322 in
323 arcs a := [b, d]
324 ; arcs b := [c, e]
325 ; arcs c := [a, f]
326 ; arcs d := [f]
327 ; arcs e := [d]
328 ; arcs f := [e]
329 ; a
330 end
331 ----
332 we could then simply write
333 [source,sml]
334 ----
335 val "VTX (1, ref [VTX (2, ref [VTX (3, ref [VTX (1, %0), \
336 \VTX (6, ref [VTX (5, ref [VTX (4, ref [VTX (6, %3)])])] as %3)]), \
337 \VTX (5, ref [VTX (4, ref [VTX (6, ref [VTX (5, %2)])])] as %2)]), \
338 \VTX (4, ref [VTX (6, ref [VTX (5, ref [VTX (4, %1)])])] as %1)] as %0)" =
339 let open Show in show (graph int) end
340 a_graph
341 ----
342
343 There is a subtle gotcha with cyclic data. Consider the following code:
344 [source,sml]
345 ----
346 exception ExnArray of exn array
347
348 val () = let
349 open Show
350 in
351 regExn (fn ExnArray a =>
352 SOME (a, C1"ExnArray" (array exn))
353 | _ => NONE)
354 end
355
356 val a_cycle = let
357 val a = Array.fromList [Empty]
358 in
359 Array.update (a, 0, ExnArray a) ; a
360 end
361 ----
362
363 Although the above looks innocent enough, the evaluation of
364 [source,sml]
365 ----
366 val "[|ExnArray %0|] as %0" =
367 let open Show in show (array exn) end
368 a_cycle
369 ----
370 goes into an infinite loop. To avoid this problem, the type-index
371 `array exn` must be evaluated only once, as in the following:
372 [source,sml]
373 ----
374 val array_exn = let open Show in array exn end
375
376 exception ExnArray of exn array
377
378 val () = let
379 open Show
380 in
381 regExn (fn ExnArray a =>
382 SOME (a, C1"ExnArray" array_exn)
383 | _ => NONE)
384 end
385
386 val a_cycle = let
387 val a = Array.fromList [Empty]
388 in
389 Array.update (a, 0, ExnArray a) ; a
390 end
391
392 val "[|ExnArray %0|] as %0" =
393 let open Show in show array_exn end
394 a_cycle
395 ----
396
397 Cyclic data (excluding closures) in Standard ML can only be
398 constructed imperatively through arrays and references (combined with
399 exceptions or recursive datatypes). Before recursing to a reference
400 or an array, one needs to check whether that reference or array has
401 already been seen before. When `ref` or `array` is called with a
402 type-index, a new cyclicity checker is instantiated.
403
404 == Implementation
405
406 [source,sml]
407 ----
408 structure SmlSyntax = struct
409 local
410 structure CV = CharVector and C = Char
411 in
412 val isSym = Char.contains "!%&$#+-/:<=>?@\\~`^|*"
413
414 fun isSymId s = 0 < size s andalso CV.all isSym s
415
416 fun isAlphaNumId s =
417 0 < size s
418 andalso C.isAlpha (CV.sub (s, 0))
419 andalso CV.all (fn c => C.isAlphaNum c
420 orelse #"'" = c
421 orelse #"_" = c) s
422
423 fun isNumLabel s =
424 0 < size s
425 andalso #"0" <> CV.sub (s, 0)
426 andalso CV.all C.isDigit s
427
428 fun isId s = isAlphaNumId s orelse isSymId s
429
430 fun isLongId s = List.all isId (String.fields (#"." <\ op =) s)
431
432 fun isLabel s = isId s orelse isNumLabel s
433 end
434 end
435
436 structure Show :> SHOW = struct
437 datatype 'a t = IN of exn list * 'a -> bool * string
438 type 'a s = 'a t
439 type ('a, 'k) p = 'a t
440 type u = unit
441 type l = unit
442
443 fun show (IN t) x = #2 (t ([], x))
444
445 (* user-defined types *)
446 fun inj inj (IN b) = IN (b o Pair.map (id, inj))
447
448 local
449 fun surround pre suf (_, s) = (false, concat [pre, s, suf])
450 fun parenthesize x = if #1 x then surround "(" ")" x else x
451 fun construct tag =
452 (fn (_, s) => (true, concat [tag, " ", s])) o parenthesize
453 fun check p m s = if p s then () else raise Fail (m^s)
454 in
455 (* tuples and records *)
456 fun (IN l) * (IN r) =
457 IN (fn (rs, a & b) =>
458 (false, concat [#2 (l (rs, a)),
459 ", ",
460 #2 (r (rs, b))]))
461
462 val U = id
463 fun L l = (check SmlSyntax.isLabel "Invalid label: " l
464 ; fn IN t => IN (surround (l^" = ") "" o t))
465
466 fun tuple (IN t) = IN (surround "(" ")" o t)
467 fun record (IN t) = IN (surround "{" "}" o t)
468
469 (* datatypes *)
470 fun (IN l) + (IN r) = IN (fn (rs, INL a) => l (rs, a)
471 | (rs, INR b) => r (rs, b))
472
473 fun C0 c = (check SmlSyntax.isId "Invalid constructor: " c
474 ; IN (const (false, c)))
475 fun C1 c (IN t) = (check SmlSyntax.isId "Invalid constructor: " c
476 ; IN (construct c o t))
477
478 val data = id
479
480 fun Y ? = Tie.iso Tie.function (fn IN x => x, IN) ?
481
482 (* exceptions *)
483 local
484 val handlers = ref ([] : (exn -> unit t option) list)
485 in
486 val exn = IN (fn (rs, e) => let
487 fun lp [] =
488 C0(concat ["<exn:",
489 General.exnName e,
490 ">"])
491 | lp (f::fs) =
492 case f e
493 of NONE => lp fs
494 | SOME t => t
495 val IN f = lp (!handlers)
496 in
497 f (rs, ())
498 end)
499 fun regExn f =
500 handlers := (Option.map
501 (fn (x, IN f) =>
502 IN (fn (rs, ()) =>
503 f (rs, x))) o f)
504 :: !handlers
505 end
506
507 (* some built-in type constructors *)
508 local
509 fun cyclic (IN t) = let
510 exception E of ''a * bool ref
511 in
512 IN (fn (rs, v : ''a) => let
513 val idx = Int.toString o length
514 fun lp (E (v', c)::rs) =
515 if v' <> v then lp rs
516 else (c := false ; (false, "%"^idx rs))
517 | lp (_::rs) = lp rs
518 | lp [] = let
519 val c = ref true
520 val r = t (E (v, c)::rs, v)
521 in
522 if !c then r
523 else surround "" (" as %"^idx rs) r
524 end
525 in
526 lp rs
527 end)
528 end
529
530 fun aggregate pre suf toList (IN t) =
531 IN (surround pre suf o
532 (fn (rs, a) =>
533 (false,
534 String.concatWith
535 ", "
536 (map (#2 o curry t rs)
537 (toList a)))))
538 in
539 fun refc ? = (cyclic o inj ! o C1"ref") ?
540 fun array ? = (cyclic o aggregate "[|" "|]" (Array.foldr op:: [])) ?
541 fun list ? = aggregate "[" "]" id ?
542 fun vector ? = aggregate "#[" "]" (Vector.foldr op:: []) ?
543 end
544
545 fun (IN _) --> (IN _) = IN (const (false, "<fn>"))
546
547 (* some built-in base types *)
548 local
549 fun mk toS = (fn x => (false, x)) o toS o (fn (_, x) => x)
550 in
551 val string =
552 IN (surround "\"" "\"" o mk (String.translate Char.toString))
553 val unit = IN (mk (fn () => "()"))
554 val bool = IN (mk Bool.toString)
555 val char = IN (surround "#\"" "\"" o mk Char.toString)
556 val int = IN (mk Int.toString)
557 val word = IN (surround "0wx" "" o mk Word.toString)
558 val real = IN (mk Real.toString)
559 end
560 end
561 end
562
563 (* Handlers for standard top-level exceptions *)
564 val () = let
565 open Show
566 fun E0 name = SOME ((), C0 name)
567 in
568 regExn (fn Bind => E0"Bind"
569 | Chr => E0"Chr"
570 | Div => E0"Div"
571 | Domain => E0"Domain"
572 | Empty => E0"Empty"
573 | Match => E0"Match"
574 | Option => E0"Option"
575 | Overflow => E0"Overflow"
576 | Size => E0"Size"
577 | Span => E0"Span"
578 | Subscript => E0"Subscript"
579 | _ => NONE)
580 ; regExn (fn Fail s => SOME (s, C1"Fail" string)
581 | _ => NONE)
582 end
583 ----
584
585
586 == Also see
587
588 There are a number of related techniques. Here are some of them.
589
590 * <<Fold#>>
591 * <<StaticSum#>>