Debian Codegraph @

doc/guide/src/Fold.adoc

raw
1 = Fold
2
3 This page describes a technique that enables convenient syntax for a
4 number of language features that are not explicitly supported by
5 <<StandardML#,Standard ML>>, including: variable number of arguments,
6 <<OptionalArguments#,optional arguments and labeled arguments>>,
7 <<ArrayLiteral#,array and vector literals>>,
8 <<FunctionalRecordUpdate#,functional record update>>,
9 and (seemingly) dependently typed functions like <<Printf#,printf>> and scanf.
10
11 The key idea to _fold_ is to define functions `fold`, `step0`,
12 and `$` such that the following equation holds.
13
14 [source,sml]
15 ----
16 fold (a, f) (step0 h1) (step0 h2) ... (step0 hn) $
17 = f (hn (... (h2 (h1 a))))
18 ----
19
20 The name `fold` comes because this is like a traditional list fold,
21 where `a` is the _base element_, and each _step function_,
22 `step0 hi`, corresponds to one element of the list and does one
23 step of the fold. The name `$` is chosen to mean "end of
24 arguments" from its common use in regular-expression syntax.
25
26 Unlike the usual list fold in which the same function is used to step
27 over each element in the list, this fold allows the step functions to
28 be different from each other, and even to be of different types. Also
29 unlike the usual list fold, this fold includes a "finishing
30 function", `f`, that is applied to the result of the fold. The
31 presence of the finishing function may seem odd because there is no
32 analogy in list fold. However, the finishing function is essential;
33 without it, there would be no way for the folder to perform an
34 arbitrary computation after processing all the arguments. The
35 examples below will make this clear.
36
37 The functions `fold`, `step0`, and `$` are easy to
38 define.
39
40 [source,sml]
41 ----
42 fun $ (a, f) = f a
43 fun id x = x
44 structure Fold =
45 struct
46 fun fold (a, f) g = g (a, f)
47 fun step0 h (a, f) = fold (h a, f)
48 end
49 ----
50
51 We've placed `fold` and `step0` in the `Fold` structure
52 but left `$` at the toplevel because it is convenient in code to
53 always have `$` in scope. We've also defined the identity
54 function, `id`, at the toplevel since we use it so frequently.
55
56 Plugging in the definitions, it is easy to verify the equation from
57 above.
58
59 [source,sml]
60 ----
61 fold (a, f) (step0 h1) (step0 h2) ... (step0 hn) $
62 = step0 h1 (a, f) (step0 h2) ... (step0 hn) $
63 = fold (h1 a, f) (step0 h2) ... (step0 hn) $
64 = step0 h2 (h1 a, f) ... (step0 hn) $
65 = fold (h2 (h1 a), f) ... (step0 hn) $
66 ...
67 = fold (hn (... (h2 (h1 a))), f) $
68 = $ (hn (... (h2 (h1 a))), f)
69 = f (hn (... (h2 (h1 a))))
70 ----
71
72
73 == Example: variable number of arguments
74
75 The simplest example of fold is accepting a variable number of
76 (curried) arguments. We'll define a function `f` and argument
77 `a` such that all of the following expressions are valid.
78
79 [source,sml]
80 ----
81 f $
82 f a $
83 f a a $
84 f a a a $
85 f a a a ... a a a $ (* as many a's as we want *)
86 ----
87
88 Off-hand it may appear impossible that all of the above expressions
89 are type correct SML -- how can a function `f` accept a variable
90 number of curried arguments? What could the type of `f` be?
91 We'll have more to say later on how type checking works. For now,
92 once we have supplied the definitions below, you can check that the
93 expressions are type correct by feeding them to your favorite SML
94 implementation.
95
96 It is simple to define `f` and `a`. We define `f` as a
97 folder whose base element is `()` and whose finish function does
98 nothing. We define `a` as the step function that does nothing.
99 The only trickiness is that we must <<EtaExpansion#,eta expand>> the
100 definition of `f` and `a` to work around the <<ValueRestriction#>>;
101 we frequently use eta expansion for this purpose without mention.
102
103 [source,sml]
104 ----
105 val base = ()
106 fun finish () = ()
107 fun step () = ()
108 val f = fn z => Fold.fold (base, finish) z
109 val a = fn z => Fold.step0 step z
110 ----
111
112 One can easily apply the fold equation to verify by hand that `f`
113 applied to any number of `a`&rsquo;s evaluates to `()`.
114
115 [source,sml]
116 ----
117 f a ... a $
118 = finish (step (... (step base)))
119 = finish (step (... ()))
120 ...
121 = finish ()
122 = ()
123 ----
124
125
126 == Example: variable-argument sum
127
128 Let's look at an example that computes something: a variable-argument
129 function `sum` and a stepper `a` such that
130
131 [source,sml]
132 ----
133 sum (a i1) (a i2) ... (a im) $ = i1 + i2 + ... + im
134 ----
135
136 The idea is simple -- the folder starts with a base accumulator of
137 `0` and the stepper adds each element to the accumulator, `s`,
138 which the folder simply returns at the end.
139
140 [source,sml]
141 ----
142 val sum = fn z => Fold.fold (0, fn s => s) z
143 fun a i = Fold.step0 (fn s => i + s)
144 ----
145
146 Using the fold equation, one can verify the following.
147
148 [source,sml]
149 ----
150 sum (a 1) (a 2) (a 3) $ = 6
151 ----
152
153
154 == Step1
155
156 It is sometimes syntactically convenient to omit the parentheses
157 around the steps in a fold. This is easily done by defining a new
158 function, `step1`, as follows.
159
160 [source,sml]
161 ----
162 structure Fold =
163 struct
164 open Fold
165 fun step1 h (a, f) b = fold (h (b, a), f)
166 end
167 ----
168
169 From the definition of `step1`, we have the following
170 equivalence.
171
172 [source,sml]
173 ----
174 fold (a, f) (step1 h) b
175 = step1 h (a, f) b
176 = fold (h (b, a), f)
177 ----
178
179 Using the above equivalence, we can compute the following equation for
180 `step1`.
181
182 [source,sml]
183 ----
184 fold (a, f) (step1 h1) b1 (step1 h2) b2 ... (step1 hn) bn $
185 = fold (h1 (b1, a), f) (step1 h2) b2 ... (step1 hn) bn $
186 = fold (h2 (b2, h1 (b1, a)), f) ... (step1 hn) bn $
187 = fold (hn (bn, ... (h2 (b2, h1 (b1, a)))), f) $
188 = f (hn (bn, ... (h2 (b2, h1 (b1, a)))))
189 ----
190
191 Here is an example using `step1` to define a variable-argument
192 product function, `prod`, with a convenient syntax.
193
194 [source,sml]
195 ----
196 val prod = fn z => Fold.fold (1, fn p => p) z
197 val ` = fn z => Fold.step1 (fn (i, p) => i * p) z
198 ----
199
200 The functions `prod` and `{backtick}` satisfy the following equation.
201 [source,sml]
202 ----
203 prod `i1 `i2 ... `im $ = i1 * i2 * ... * im
204 ----
205
206 Note that in SML, `{backtick}i1` is two different tokens, `{backtick}` and
207 `i1`. We often use `{backtick}` for an instance of a `step1` function
208 because of its syntactic unobtrusiveness and because no space is
209 required to separate it from an alphanumeric token.
210
211 Also note that there are no parenthesis around the steps. That is,
212 the following expression is not the same as the above one (in fact, it
213 is not type correct).
214
215 [source,sml]
216 ----
217 prod (`i1) (`i2) ... (`im) $
218 ----
219
220
221 == Example: list literals
222
223 SML already has a syntax for list literals, e.g. `[w, x, y, z]`.
224 However, using fold, we can define our own syntax.
225
226 [source,sml]
227 ----
228 val list = fn z => Fold.fold ([], rev) z
229 val ` = fn z => Fold.step1 (op ::) z
230 ----
231
232 The idea is that the folder starts out with the empty list, the steps
233 accumulate the elements into a list, and then the finishing function
234 reverses the list at the end.
235
236 With these definitions one can write a list like:
237
238 [source,sml]
239 ----
240 list `w `x `y `z $
241 ----
242
243 While the example is not practically useful, it does demonstrate the
244 need for the finishing function to be incorporated in `fold`.
245 Without a finishing function, every use of `list` would need to be
246 wrapped in `rev`, as follows.
247
248 [source,sml]
249 ----
250 rev (list `w `x `y `z $)
251 ----
252
253 The finishing function allows us to incorporate the reversal into the
254 definition of `list`, and to treat `list` as a truly variable
255 argument function, performing an arbitrary computation after receiving
256 all of its arguments.
257
258 See <<ArrayLiteral#>> for a similar use of `fold` that provides a
259 syntax for array and vector literals, which are not built in to SML.
260
261
262 == Fold right
263
264 Just as `fold` is analogous to a fold left, in which the functions
265 are applied to the accumulator left-to-right, we can define a variant
266 of `fold` that is analogous to a fold right, in which the
267 functions are applied to the accumulator right-to-left. That is, we
268 can define functions `foldr` and `step0` such that the
269 following equation holds.
270
271 [source,sml]
272 ----
273 foldr (a, f) (step0 h1) (step0 h2) ... (step0 hn) $
274 = f (h1 (h2 (... (hn a))))
275 ----
276
277 The implementation of fold right is easy, using fold. The idea is for
278 the fold to start with `f` and for each step to precompose the
279 next `hi`. Then, the finisher applies the composed function to
280 the base value, `a`. Here is the code.
281
282 [source,sml]
283 ----
284 structure Foldr =
285 struct
286 fun foldr (a, f) = Fold.fold (f, fn g => g a)
287 fun step0 h = Fold.step0 (fn g => g o h)
288 end
289 ----
290
291 Verifying the fold-right equation is straightforward, using the
292 fold-left equation.
293
294 [source,sml]
295 ----
296 foldr (a, f) (Foldr.step0 h1) (Foldr.step0 h2) ... (Foldr.step0 hn) $
297 = fold (f, fn g => g a)
298 (Fold.step0 (fn g => g o h1))
299 (Fold.step0 (fn g => g o h2))
300 ...
301 (Fold.step0 (fn g => g o hn)) $
302 = (fn g => g a)
303 ((fn g => g o hn) (... ((fn g => g o h2) ((fn g => g o h1) f))))
304 = (fn g => g a)
305 ((fn g => g o hn) (... ((fn g => g o h2) (f o h1))))
306 = (fn g => g a) ((fn g => g o hn) (... (f o h1 o h2)))
307 = (fn g => g a) (f o h1 o h2 o ... o hn)
308 = (f o h1 o h2 o ... o hn) a
309 = f (h1 (h2 (... (hn a))))
310 ----
311
312 One can also define the fold-right analogue of `step1`.
313
314 [source,sml]
315 ----
316 structure Foldr =
317 struct
318 open Foldr
319 fun step1 h = Fold.step1 (fn (b, g) => g o (fn a => h (b, a)))
320 end
321 ----
322
323
324 == Example: list literals via fold right
325
326 Revisiting the list literal example from earlier, we can use fold
327 right to define a syntax for list literals that doesn't do a reversal.
328
329 [source,sml]
330 ----
331 val list = fn z => Foldr.foldr ([], fn l => l) z
332 val ` = fn z => Foldr.step1 (op ::) z
333 ----
334
335 As before, with these definitions, one can write a list like:
336
337 [source,sml]
338 ----
339 list `w `x `y `z $
340 ----
341
342 The difference between the fold-left and fold-right approaches is that
343 the fold-right approach does not have to reverse the list at the end,
344 since it accumulates the elements in the correct order. In practice,
345 MLton will simplify away all of the intermediate function composition,
346 so the the fold-right approach will be more efficient.
347
348
349 == Mixing steppers
350
351 All of the examples so far have used the same step function throughout
352 a fold. This need not be the case. For example, consider the
353 following.
354
355 [source,sml]
356 ----
357 val n = fn z => Fold.fold (0, fn i => i) z
358 val O = fn z => Fold.step0 (fn i => i * 2) z
359 val I = fn z => Fold.step0 (fn i => i * 2 + 1) z
360 ----
361
362 Here we have one folder, `n`, that can be used with two different
363 steppers, `O` and `I`. By using the fold equation, one can
364 verify the following equations.
365
366 [source,sml]
367 ----
368 n O $ = 0
369 n I $ = 1
370 n I O $ = 2
371 n I O I $ = 5
372 n I I I O $ = 14
373 ----
374
375 That is, we've defined a syntax for writing binary integer constants.
376
377 Not only can one use different instances of `step0` in the same
378 fold, one can also intermix uses of `step0` and `step1`. For
379 example, consider the following.
380
381 [source,sml]
382 ----
383 val n = fn z => Fold.fold (0, fn i => i) z
384 val O = fn z => Fold.step0 (fn i => n * 8) z
385 val ` = fn z => Fold.step1 (fn (i, n) => n * 8 + i) z
386 ----
387
388 Using the straightforward generalization of the fold equation to mixed
389 steppers, one can verify the following equations.
390
391 [source,sml]
392 ----
393 n 0 $ = 0
394 n `3 O $ = 24
395 n `1 O `7 $ = 71
396 ----
397
398 That is, we've defined a syntax for writing octal integer constants,
399 with a special syntax, `O`, for the zero digit (admittedly
400 contrived, since one could just write `{backtick}0` instead of `O`).
401
402 See <<NumericLiteral#>> for a practical extension of this approach that
403 supports numeric constants in any base and of any type.
404
405
406 == (Seemingly) dependent types
407
408 A normal list fold always returns the same type no matter what
409 elements are in the list or how long the list is. Variable-argument
410 fold is more powerful, because the result type can vary based both on
411 the arguments that are passed and on their number. This can provide
412 the illusion of dependent types.
413
414 For example, consider the following.
415
416 [source,sml]
417 ----
418 val f = fn z => Fold.fold ((), id) z
419 val a = fn z => Fold.step0 (fn () => "hello") z
420 val b = fn z => Fold.step0 (fn () => 13) z
421 val c = fn z => Fold.step0 (fn () => (1, 2)) z
422 ----
423
424 Using the fold equation, one can verify the following equations.
425
426 [source,sml]
427 ----
428 f a $ = "hello": string
429 f b $ = 13: int
430 f c $ = (1, 2): int * int
431 ----
432
433 That is, `f` returns a value of a different type depending on
434 whether it is applied to argument `a`, argument `b`, or
435 argument `c`.
436
437 The following example shows how the type of a fold can depend on the
438 number of arguments.
439
440 [source,sml]
441 ----
442 val grow = fn z => Fold.fold ([], fn l => l) z
443 val a = fn z => Fold.step0 (fn x => [x]) z
444 ----
445
446 Using the fold equation, one can verify the following equations.
447
448 [source,sml]
449 ----
450 grow $ = []: 'a list
451 grow a $ = [[]]: 'a list list
452 grow a a $ = [[[]]]: 'a list list list
453 ----
454
455 Clearly, the result type of a call to the variable argument `grow`
456 function depends on the number of arguments that are passed.
457
458 As a reminder, this is well-typed SML. You can check it out in any
459 implementation.
460
461
462 == (Seemingly) dependently-typed functional results
463
464 Fold is especially useful when it returns a curried function whose
465 arity depends on the number of arguments. For example, consider the
466 following.
467
468 [source,sml]
469 ----
470 val makeSum = fn z => Fold.fold (id, fn f => f 0) z
471 val I = fn z => Fold.step0 (fn f => fn i => fn x => f (x + i)) z
472 ----
473
474 The `makeSum` folder constructs a function whose arity depends on
475 the number of `I` arguments and that adds together all of its
476 arguments. For example,
477 `makeSum I $` is of type `int \-> int` and
478 `makeSum I I $` is of type `int \-> int \-> int`.
479
480 One can use the fold equation to verify that the `makeSum` works
481 correctly. For example, one can easily check by hand the following
482 equations.
483
484 [source,sml]
485 ----
486 makeSum I $ 1 = 1
487 makeSum I I $ 1 2 = 3
488 makeSum I I I $ 1 2 3 = 6
489 ----
490
491 Returning a function becomes especially interesting when there are
492 steppers of different types. For example, the following `makeSum`
493 folder constructs functions that sum integers and reals.
494
495 [source,sml]
496 ----
497 val makeSum = fn z => Foldr.foldr (id, fn f => f 0.0) z
498 val I = fn z => Foldr.step0 (fn f => fn x => fn i => f (x + real i)) z
499 val R = fn z => Foldr.step0 (fn f => fn x: real => fn r => f (x + r)) z
500 ----
501
502 With these definitions, `makeSum I R $` is of type
503 `int \-> real \-> real` and `makeSum R I I $` is of type
504 `real \-> int \-> int \-> real`. One can use the foldr equation to
505 check the following equations.
506
507 [source,sml]
508 ----
509 makeSum I $ 1 = 1.0
510 makeSum I R $ 1 2.5 = 3.5
511 makeSum R I I $ 1.5 2 3 = 6.5
512 ----
513
514 We used `foldr` instead of `fold` for this so that the order
515 in which the specifiers `I` and `R` appear is the same as the
516 order in which the arguments appear. Had we used `fold`, things
517 would have been reversed.
518
519 An extension of this idea is sufficient to define <<Printf#>>-like
520 functions in SML.
521
522
523 == An idiom for combining steps
524
525 It is sometimes useful to combine a number of steps together and name
526 them as a single step. As a simple example, suppose that one often
527 sees an integer follower by a real in the `makeSum` example above.
528 One can define a new _compound step_ `IR` as follows.
529
530 [source,sml]
531 ----
532 val IR = fn u => Fold.fold u I R
533 ----
534
535 With this definition in place, one can verify the following.
536
537 [source,sml]
538 ----
539 makeSum IR IR $ 1 2.2 3 4.4 = 10.6
540 ----
541
542 In general, one can combine steps `s1`, `s2`, ... `sn` as
543
544 [source,sml]
545 ----
546 fn u => Fold.fold u s1 s2 ... sn
547 ----
548
549 The following calculation shows why a compound step behaves as the
550 composition of its constituent steps.
551
552 [source,sml]
553 ----
554 fold u (fn u => fold u s1 s2 ... sn)
555 = (fn u => fold u s1 s2 ... sn) u
556 = fold u s1 s2 ... sn
557 ----
558
559
560 == Post composition
561
562 Suppose we already have a function defined via fold,
563 `w = fold (a, f)`, and we would like to construct a new fold
564 function that is like `w`, but applies `g` to the result
565 produced by `w`. This is similar to function composition, but we
566 can't just do `g o w`, because we don't want to use `g` until
567 `w` has been applied to all of its arguments and received the
568 end-of-arguments terminator `$`.
569
570 More precisely, we want to define a post-composition function
571 `post` that satisfies the following equation.
572
573 [source,sml]
574 ----
575 post (w, g) s1 ... sn $ = g (w s1 ... sn $)
576 ----
577
578 Here is the definition of `post`.
579
580 [source,sml]
581 ----
582 structure Fold =
583 struct
584 open Fold
585 fun post (w, g) s = w (fn (a, h) => s (a, g o h))
586 end
587 ----
588
589 The following calculations show that `post` satisfies the desired
590 equation, where `w = fold (a, f)`.
591
592 [source,sml]
593 ----
594 post (w, g) s
595 = w (fn (a, h) => s (a, g o h))
596 = fold (a, f) (fn (a, h) => s (a, g o h))
597 = (fn (a, h) => s (a, g o h)) (a, f)
598 = s (a, g o f)
599 = fold (a, g o f) s
600 ----
601
602 Now, suppose `si = step0 hi` for `i` from `1` to `n`.
603
604 [source,sml]
605 ----
606 post (w, g) s1 s2 ... sn $
607 = fold (a, g o f) s1 s2 ... sn $
608 = (g o f) (hn (... (h1 a)))
609 = g (f (hn (... (h1 a))))
610 = g (fold (a, f) s1 ... sn $)
611 = g (w s1 ... sn $)
612 ----
613
614 For a practical example of post composition, see <<ArrayLiteral#>>.
615
616
617 == Lift
618
619 We now define a peculiar-looking function, `lift0`, that is,
620 equationally speaking, equivalent to the identity function on a step
621 function.
622
623 [source,sml]
624 ----
625 fun lift0 s (a, f) = fold (fold (a, id) s $, f)
626 ----
627
628 Using the definitions, we can prove the following equation.
629
630 [source,sml]
631 ----
632 fold (a, f) (lift0 (step0 h)) = fold (a, f) (step0 h)
633 ----
634
635 Here is the proof.
636
637 [source,sml]
638 ----
639 fold (a, f) (lift0 (step0 h))
640 = lift0 (step0 h) (a, f)
641 = fold (fold (a, id) (step0 h) $, f)
642 = fold (step0 h (a, id) $, f)
643 = fold (fold (h a, id) $, f)
644 = fold ($ (h a, id), f)
645 = fold (id (h a), f)
646 = fold (h a, f)
647 = step0 h (a, f)
648 = fold (a, f) (step0 h)
649 ----
650
651 If `lift0` is the identity, then why even define it? The answer
652 lies in the typing of fold expressions, which we have, until now, left
653 unexplained.
654
655
656 == Typing
657
658 Perhaps the most surprising aspect of fold is that it can be checked
659 by the SML type system. The types involved in fold expressions are
660 complex; fortunately type inference is able to deduce them.
661 Nevertheless, it is instructive to study the types of fold functions
662 and steppers. More importantly, it is essential to understand the
663 typing aspects of fold in order to write down signatures of functions
664 defined using fold and step.
665
666 Here is the `FOLD` signature, and a recapitulation of the entire
667 `Fold` structure, with additional type annotations.
668
669 [source,sml]
670 ----
671 signature FOLD =
672 sig
673 type ('a, 'b, 'c, 'd) step = 'a * ('b -> 'c) -> 'd
674 type ('a, 'b, 'c, 'd) t = ('a, 'b, 'c, 'd) step -> 'd
675 type ('a1, 'a2, 'b, 'c, 'd) step0 =
676 ('a1, 'b, 'c, ('a2, 'b, 'c, 'd) t) step
677 type ('a11, 'a12, 'a2, 'b, 'c, 'd) step1 =
678 ('a12, 'b, 'c, 'a11 -> ('a2, 'b, 'c, 'd) t) step
679
680 val fold: 'a * ('b -> 'c) -> ('a, 'b, 'c, 'd) t
681 val lift0: ('a1, 'a2, 'a2, 'a2, 'a2) step0
682 -> ('a1, 'a2, 'b, 'c, 'd) step0
683 val post: ('a, 'b, 'c1, 'd) t * ('c1 -> 'c2)
684 -> ('a, 'b, 'c2, 'd) t
685 val step0: ('a1 -> 'a2) -> ('a1, 'a2, 'b, 'c, 'd) step0
686 val step1: ('a11 * 'a12 -> 'a2)
687 -> ('a11, 'a12, 'a2, 'b, 'c, 'd) step1
688 end
689
690 structure Fold:> FOLD =
691 struct
692 type ('a, 'b, 'c, 'd) step = 'a * ('b -> 'c) -> 'd
693
694 type ('a, 'b, 'c, 'd) t = ('a, 'b, 'c, 'd) step -> 'd
695
696 type ('a1, 'a2, 'b, 'c, 'd) step0 =
697 ('a1, 'b, 'c, ('a2, 'b, 'c, 'd) t) step
698
699 type ('a11, 'a12, 'a2, 'b, 'c, 'd) step1 =
700 ('a12, 'b, 'c, 'a11 -> ('a2, 'b, 'c, 'd) t) step
701
702 fun fold (a: 'a, f: 'b -> 'c)
703 (g: ('a, 'b, 'c, 'd) step): 'd =
704 g (a, f)
705
706 fun step0 (h: 'a1 -> 'a2)
707 (a1: 'a1, f: 'b -> 'c): ('a2, 'b, 'c, 'd) t =
708 fold (h a1, f)
709
710 fun step1 (h: 'a11 * 'a12 -> 'a2)
711 (a12: 'a12, f: 'b -> 'c)
712 (a11: 'a11): ('a2, 'b, 'c, 'd) t =
713 fold (h (a11, a12), f)
714
715 fun lift0 (s: ('a1, 'a2, 'a2, 'a2, 'a2) step0)
716 (a: 'a1, f: 'b -> 'c): ('a2, 'b, 'c, 'd) t =
717 fold (fold (a, id) s $, f)
718
719 fun post (w: ('a, 'b, 'c1, 'd) t,
720 g: 'c1 -> 'c2)
721 (s: ('a, 'b, 'c2, 'd) step): 'd =
722 w (fn (a, h) => s (a, g o h))
723 end
724 ----
725
726 That's a lot to swallow, so let's walk through it one step at a time.
727 First, we have the definition of type `Fold.step`.
728
729 [source,sml]
730 ----
731 type ('a, 'b, 'c, 'd) step = 'a * ('b -> 'c) -> 'd
732 ----
733
734 As a fold proceeds over its arguments, it maintains two things: the
735 accumulator, of type `'a`, and the finishing function, of type
736 `'b \-> 'c`. Each step in the fold is a function that takes those
737 two pieces (i.e. `'a * ('b \-> 'c)` and does something to them
738 (i.e. produces `'d`). The result type of the step is completely
739 left open to be filled in by type inference, as it is an arrow type
740 that is capable of consuming the rest of the arguments to the fold.
741
742 A folder, of type `Fold.t`, is a function that consumes a single
743 step.
744
745 [source,sml]
746 ----
747 type ('a, 'b, 'c, 'd) t = ('a, 'b, 'c, 'd) step -> 'd
748 ----
749
750 Expanding out the type, we have:
751
752 [source,sml]
753 ----
754 type ('a, 'b, 'c, 'd) t = ('a * ('b -> 'c) -> 'd) -> 'd
755 ----
756
757 This shows that the only thing a folder does is to hand its
758 accumulator (`'a`) and finisher (`'b \-> 'c`) to the next step
759 (`'a * ('b \-> 'c) \-> 'd`). If SML had <<FirstClassPolymorphism#,first-class polymorphism>>,
760 we would write the fold type as follows.
761
762 [source,sml]
763 ----
764 type ('a, 'b, 'c) t = Forall 'd . ('a, 'b, 'c, 'd) step -> 'd
765 ----
766
767 This type definition shows that a folder had nothing to do with
768 the rest of the fold, it only deals with the next step.
769
770 We now can understand the type of `fold`, which takes the initial
771 value of the accumulator and the finishing function, and constructs a
772 folder, i.e. a function awaiting the next step.
773
774 [source,sml]
775 ----
776 val fold: 'a * ('b -> 'c) -> ('a, 'b, 'c, 'd) t
777 fun fold (a: 'a, f: 'b -> 'c)
778 (g: ('a, 'b, 'c, 'd) step): 'd =
779 g (a, f)
780 ----
781
782 Continuing on, we have the type of step functions.
783
784 [source,sml]
785 ----
786 type ('a1, 'a2, 'b, 'c, 'd) step0 =
787 ('a1, 'b, 'c, ('a2, 'b, 'c, 'd) t) step
788 ----
789
790 Expanding out the type a bit gives:
791
792 [source,sml]
793 ----
794 type ('a1, 'a2, 'b, 'c, 'd) step0 =
795 'a1 * ('b -> 'c) -> ('a2, 'b, 'c, 'd) t
796 ----
797
798 So, a step function takes the accumulator (`'a1`) and finishing
799 function (`'b \-> 'c`), which will be passed to it by the previous
800 folder, and transforms them to a new folder. This new folder has a
801 new accumulator (`'a2`) and the same finishing function.
802
803 Again, imagining that SML had <<FirstClassPolymorphism#,first-class polymorphism>> makes the type
804 clearer.
805
806 [source,sml]
807 ----
808 type ('a1, 'a2) step0 =
809 Forall ('b, 'c) . ('a1, 'b, 'c, ('a2, 'b, 'c) t) step
810 ----
811
812 Thus, in essence, a `step0` function is a wrapper around a
813 function of type `'a1 \-> 'a2`, which is exactly what the
814 definition of `step0` does.
815
816 [source,sml]
817 ----
818 val step0: ('a1 -> 'a2) -> ('a1, 'a2, 'b, 'c, 'd) step0
819 fun step0 (h: 'a1 -> 'a2)
820 (a1: 'a1, f: 'b -> 'c): ('a2, 'b, 'c, 'd) t =
821 fold (h a1, f)
822 ----
823
824 It is not much beyond `step0` to understand `step1`.
825
826 [source,sml]
827 ----
828 type ('a11, 'a12, 'a2, 'b, 'c, 'd) step1 =
829 ('a12, 'b, 'c, 'a11 -> ('a2, 'b, 'c, 'd) t) step
830 ----
831
832 A `step1` function takes the accumulator (`'a12`) and finisher
833 (`'b \-> 'c`) passed to it by the previous folder and transforms
834 them into a function that consumes the next argument (`'a11`) and
835 produces a folder that will continue the fold with a new accumulator
836 (`'a2`) and the same finisher.
837
838 [source,sml]
839 ----
840 fun step1 (h: 'a11 * 'a12 -> 'a2)
841 (a12: 'a12, f: 'b -> 'c)
842 (a11: 'a11): ('a2, 'b, 'c, 'd) t =
843 fold (h (a11, a12), f)
844 ----
845
846 With <<FirstClassPolymorphism#,first-class polymorphism>>, a `step1` function is more clearly
847 seen as a wrapper around a binary function of type
848 `'a11 * 'a12 \-> 'a2`.
849
850 [source,sml]
851 ----
852 type ('a11, 'a12, 'a2) step1 =
853 Forall ('b, 'c) . ('a12, 'b, 'c, 'a11 -> ('a2, 'b, 'c) t) step
854 ----
855
856 The type of `post` is clear: it takes a folder with a finishing
857 function that produces type `'c1`, and a function of type
858 `'c1 \-> 'c2` to postcompose onto the folder. It returns a new
859 folder with a finishing function that produces type `'c2`.
860
861 [source,sml]
862 ----
863 val post: ('a, 'b, 'c1, 'd) t * ('c1 -> 'c2)
864 -> ('a, 'b, 'c2, 'd) t
865 fun post (w: ('a, 'b, 'c1, 'd) t,
866 g: 'c1 -> 'c2)
867 (s: ('a, 'b, 'c2, 'd) step): 'd =
868 w (fn (a, h) => s (a, g o h))
869 ----
870
871 We will return to `lift0` after an example.
872
873
874 == An example typing
875
876 Let's type check our simplest example, a variable-argument fold.
877 Recall that we have a folder `f` and a stepper `a` defined as
878 follows.
879
880 [source,sml]
881 ----
882 val f = fn z => Fold.fold ((), fn () => ()) z
883 val a = fn z => Fold.step0 (fn () => ()) z
884 ----
885
886 Since the accumulator and finisher are uninteresting, we'll use some
887 abbreviations to simplify things.
888
889 [source,sml]
890 ----
891 type 'd step = (unit, unit, unit, 'd) Fold.step
892 type 'd fold = 'd step -> 'd
893 ----
894
895 With these abbreviations, `f` and `a` have the following polymorphic
896 types.
897
898 [source,sml]
899 ----
900 f: 'd fold
901 a: 'd step
902 ----
903
904 Suppose we want to type check
905
906 [source,sml]
907 ----
908 f a a a $: unit
909 ----
910
911 As a reminder, the fully parenthesized expression is
912 [source,sml]
913 ----
914 ((((f a) a) a) a) $
915 ----
916
917 The observation that we will use repeatedly is that for any type
918 `z`, if `f: z fold` and `s: z step`, then `f s: z`.
919 So, if we want
920
921 [source,sml]
922 ----
923 (f a a a) $: unit
924 ----
925
926 then we must have
927
928 [source,sml]
929 ----
930 f a a a: unit fold
931 $: unit step
932 ----
933
934 Applying the observation again, we must have
935
936 [source,sml]
937 ----
938 f a a: unit fold fold
939 a: unit fold step
940 ----
941
942 Applying the observation two more times leads to the following type
943 derivation.
944
945 [source,sml]
946 ----
947 f: unit fold fold fold fold a: unit fold fold fold step
948 f a: unit fold fold fold a: unit fold fold step
949 f a a: unit fold fold a: unit fold step
950 f a a a: unit fold $: unit step
951 f a a a $: unit
952 ----
953
954 So, each application is a fold that consumes the next step, producing
955 a fold of one smaller type.
956
957 One can expand some of the type definitions in `f` to see that it is
958 indeed a function that takes four curried arguments, each one a step
959 function.
960
961 [source,sml]
962 ----
963 f: unit fold fold fold step
964 -> unit fold fold step
965 -> unit fold step
966 -> unit step
967 -> unit
968 ----
969
970 This example shows why we must eta expand uses of `fold` and `step0`
971 to work around the value restriction and make folders and steppers
972 polymorphic. The type of a fold function like `f` depends on the
973 number of arguments, and so will vary from use to use. Similarly,
974 each occurrence of an argument like `a` has a different type,
975 depending on the number of remaining arguments.
976
977 This example also shows that the type of a folder, when fully
978 expanded, is exponential in the number of arguments: there are as many
979 nested occurrences of the `fold` type constructor as there are
980 arguments, and each occurrence duplicates its type argument. One can
981 observe this exponential behavior in a type checker that doesn't share
982 enough of the representation of types (e.g. one that represents types
983 as trees rather than directed acyclic graphs).
984
985 Generalizing this type derivation to uses of fold where the
986 accumulator and finisher are more interesting is straightforward. One
987 simply includes the type of the accumulator, which may change, for
988 each step, and the type of the finisher, which doesn't change from
989 step to step.
990
991
992 == Typing lift
993
994 The lack of <<FirstClassPolymorphism#,first-class polymorphism>> in SML
995 causes problems if one wants to use a step in a first-class way.
996 Consider the following `double` function, which takes a step, `s`, and
997 produces a composite step that does `s` twice.
998
999 [source,sml]
1000 ----
1001 fun double s = fn u => Fold.fold u s s
1002 ----
1003
1004 The definition of `double` is not type correct. The problem is that
1005 the type of a step depends on the number of remaining arguments but
1006 that the parameter `s` is not polymorphic, and so can not be used in
1007 two different positions.
1008
1009 Fortunately, we can define a function, `lift0`, that takes a monotyped
1010 step function and _lifts_ it into a polymorphic step function. This
1011 is apparent in the type of `lift0`.
1012
1013 [source,sml]
1014 ----
1015 val lift0: ('a1, 'a2, 'a2, 'a2, 'a2) step0
1016 -> ('a1, 'a2, 'b, 'c, 'd) step0
1017 fun lift0 (s: ('a1, 'a2, 'a2, 'a2, 'a2) step0)
1018 (a: 'a1, f: 'b -> 'c): ('a2, 'b, 'c, 'd) t =
1019 fold (fold (a, id) s $, f)
1020 ----
1021
1022 The following definition of `double` uses `lift0`, appropriately eta
1023 wrapped, to fix the problem.
1024
1025 [source,sml]
1026 ----
1027 fun double s =
1028 let
1029 val s = fn z => Fold.lift0 s z
1030 in
1031 fn u => Fold.fold u s s
1032 end
1033 ----
1034
1035 With that definition of `double` in place, we can use it as in the
1036 following example.
1037
1038 [source,sml]
1039 ----
1040 val f = fn z => Fold.fold ((), fn () => ()) z
1041 val a = fn z => Fold.step0 (fn () => ()) z
1042 val a2 = fn z => double a z
1043 val () = f a a2 a a2 $
1044 ----
1045
1046 Of course, we must eta wrap the call `double` in order to use its
1047 result, which is a step function, polymorphically.
1048
1049
1050 == Hiding the type of the accumulator
1051
1052 For clarity and to avoid mistakes, it can be useful to hide the type
1053 of the accumulator in a fold. Reworking the simple variable-argument
1054 example to do this leads to the following.
1055
1056 [source,sml]
1057 ----
1058 structure S:>
1059 sig
1060 type ac
1061 val f: (ac, ac, unit, 'd) Fold.t
1062 val s: (ac, ac, 'b, 'c, 'd) Fold.step0
1063 end =
1064 struct
1065 type ac = unit
1066 val f = fn z => Fold.fold ((), fn () => ()) z
1067 val s = fn z => Fold.step0 (fn () => ()) z
1068 end
1069 ----
1070
1071 The idea is to name the accumulator type and use opaque signature
1072 matching to make it abstract. This can prevent improper manipulation
1073 of the accumulator by client code and ensure invariants that the
1074 folder and stepper would like to maintain.
1075
1076 For a practical example of this technique, see <<ArrayLiteral#>>.
1077
1078
1079 == Also see
1080
1081 Fold has a number of practical applications. Here are some of them.
1082
1083 * <<ArrayLiteral#>>
1084 * <<Fold01N#>>
1085 * <<FunctionalRecordUpdate#>>
1086 * <<NumericLiteral#>>
1087 * <<OptionalArguments#>>
1088 * <<Printf#>>
1089 * <<VariableArityPolymorphism#>>
1090
1091 There are a number of related techniques. Here are some of them.
1092
1093 * <<StaticSum#>>
1094 * <<TypeIndexedValues#>>