Debian Codegraph @

doc/guide/src/ArrayLiteral.adoc

raw
1 = ArrayLiteral
2
3 <<StandardML#,Standard ML>> does not have a syntax for array literals or
4 vector literals. The only way to write down an array is like
5 [source,sml]
6 ----
7 Array.fromList [w, x, y, z]
8 ----
9
10 No SML compiler produces efficient code for the above expression. The
11 generated code allocates a list and then converts it to an array. To
12 alleviate this, one could write down the same array using
13 `Array.tabulate`, or even using `Array.array` and `Array.update`, but
14 that is syntactically unwieldy.
15
16 Fortunately, using <<Fold#>>, it is possible to define constants `A`,
17 and `{backtick}` so that one can write down an array like:
18 [source,sml]
19 ----
20 A `w `x `y `z $
21 ----
22 This is as syntactically concise as the `fromList` expression.
23 Furthermore, MLton, at least, will generate the efficient code as if
24 one had written down a use of `Array.array` followed by four uses of
25 `Array.update`.
26
27 Along with `A` and `{backtick}`, one can define a constant `V` that makes
28 it possible to define vector literals with the same syntax, e.g.,
29 [source,sml]
30 ----
31 V `w `x `y `z $
32 ----
33
34 Note that the same element indicator, `{backtick}`, serves for both array
35 and vector literals. Of course, the `$` is the end-of-arguments
36 marker always used with <<Fold#>>. The only difference between an
37 array literal and vector literal is the `A` or `V` at the beginning.
38
39 Here is the implementation of `A`, `V`, and `{backtick}`. We place them
40 in a structure and use signature abstraction to hide the type of the
41 accumulator. See <<Fold#>> for more on this technique.
42 [source,sml]
43 ----
44 structure Literal:>
45 sig
46 type 'a z
47 val A: ('a z, 'a z, 'a array, 'd) Fold.t
48 val V: ('a z, 'a z, 'a vector, 'd) Fold.t
49 val ` : ('a, 'a z, 'a z, 'b, 'c, 'd) Fold.step1
50 end =
51 struct
52 type 'a z = int * 'a option * ('a array -> unit)
53
54 val A =
55 fn z =>
56 Fold.fold
57 ((0, NONE, ignore),
58 fn (n, opt, fill) =>
59 case opt of
60 NONE =>
61 Array.tabulate (0, fn _ => raise Fail "array0")
62 | SOME x =>
63 let
64 val a = Array.array (n, x)
65 val () = fill a
66 in
67 a
68 end)
69 z
70
71 val V = fn z => Fold.post (A, Array.vector) z
72
73 val ` =
74 fn z =>
75 Fold.step1
76 (fn (x, (i, opt, fill)) =>
77 (i + 1,
78 SOME x,
79 fn a => (Array.update (a, i, x); fill a)))
80 z
81 end
82 ----
83
84 The idea of the code is for the fold to accumulate a count of the
85 number of elements, a sample element, and a function that fills in all
86 the elements. When the fold is complete, the finishing function
87 allocates the array, applies the fill function, and returns the array.
88 The only difference between `A` and `V` is at the very end; `A` just
89 returns the array, while `V` converts it to a vector using
90 post-composition, which is further described on the <<Fold#>> page.