sourcework/libs/Equations/src/Equations.xtlm
1⍝│ Equations: its macro library -- e_q<, t_ex< and b_oth<: an equation as
2⍝│ printed in a paper, to its value, its LaTeX, or both.
3⍝│ Imported with the functions, under one alias: "e:" u_se< "Equations".
4⍝│ A macro is a function from the source text written left and right of
5⍝│ its call to the source that replaces the call, run before the program
6⍝│ is compiled (X_eTaL MC10). Names with m: are macros; those under h: are
7⍝│ private to this file.
8
9"t:" u̲se< "Strings"
10"pa:" u̲se< "Parsing"
11
12⍝━━ The macros
13
14⍝│ The value of an equation written as a paper prints it. The left names
15⍝│ the result, its free indices and their extents ("Y[o,h,w] | O Ho Wo",
16⍝│ or "L[] | " for a scalar). The right is an expression over the free
17⍝│ indices in which a parenthesized sum is a term:
18⍝│ "(sum j:=0..M-1 | W[i,j] * x[j]) + b[i]"
19⍝│ A sum is an operator word (sum, prod, max, min), an index, := and an
20⍝│ inclusive range low..high, then | and its body; several, separated by
21⍝│ commas, nest outermost first. A right side that is one bare sum needs
22⍝│ no parentheses: "sum c:=0..C-1, sum r:=0..Kh-1 | X[c,h+r] * W[c,r]".
23⍝│ The word integral binds a continuous variable over Float bounds and
24⍝│ takes the value of its body by a quadrature rule written after by:
25⍝│ "integral tau:=0..1 by simpson 64 | exp(tau)" (trapezoid or simpson,
26⍝│ then the number of steps; without by, trapezoid 64; simpson needs an
27⍝│ even number). The variable is the grid of n + 1 points a, a + h, ...,
28⍝│ b; a bound of inf is refused (write a truncation and show the tail is
29⍝│ small, or change variables). Trapezoid is exact on lines, simpson on
30⍝│ cubics; at a jump of the body the sample takes the body's value at
31⍝│ that point as written.
32⍝│ Expressions follow math precedence: ^ binds tightest (right to left),
33⍝│ then * and /, then + and - (left to right); parentheses group; the
34⍝│ functions are exp(x), log(x), sqrt(x), abs(x), sin(x), cos(x),
35⍝│ max(a, b) and min(a, b); A[e1,e2] reads one element of the caller's array A, one
36⍝│ index per axis, from 0. Every reading rule uses all of its text or
37⍝│ refuses the call, and what was read is written back and compared
38⍝│ with the text at every call, so nothing written is ever dropped.
39⍝│ Both sides are notations (X_eTaL MC32): where a program is drawn
40⍝│ (the pages, the live demo, xetal render --html) the call's two
41⍝│ strings are shown as one math box, what e:t_ex< gives for them,
42⍝│ after the macro's name; the value and the text are unchanged.
43⍝│ takes: notation notation
44⍝│ draws: t_ex<
45⍝│ uses: parsed
46ᵐe̲q< ← { lhs rhs → (ʰf̲ree lhs) ʰv̲alue ʰc̲hecked rhs }
47
48⍝│ The LaTeX of the same call, a string: the result as written (L for a
49⍝│ scalar, Y_{o,h,w} for an array), then = and the expression, with
50⍝│ \sum \prod \max \min, \int_{a}^{b} ... \, d\tau for an integral (a
51⍝│ Greek letter's name as its command), \frac for a quotient, \sqrt \exp
52⍝│ \log \sin \cos, and the brackets as subscripts.
53⍝│ takes: text text
54⍝│ uses: parsed
55ᵐt̲ex< ← { lhs rhs → "\"" c̲at (lhs ʰt̲ex ʰc̲hecked rhs) c̲at "\"" }
56
57⍝│ Both from one call: the pair (value, LaTeX); drawn as e:e_q< is.
58⍝│ takes: notation notation
59⍝│ draws: t_ex<
60⍝│ uses: parsed
61ᵐb̲oth< ← { lhs rhs → "(" c̲at ((ʰf̲ree lhs) ʰv̲alue ʰc̲hecked rhs) c̲at ", \"" c̲at (lhs ʰt̲ex ʰc̲hecked rhs) c̲at "\")" }
62
63⍝│ Discrete 1-D convolution and cross-correlation, written as the
64⍝│ sums they are (X_eTaL Saga 42 decision 5: library macros over sum,
65⍝│ not words of the grammar). The left names the result, its index and
66⍝│ the boundary mode, "y[n] | full"; the right names the signal and the
67⍝│ kernel, two of the caller's vectors, "x h". The modes: full gives
68⍝│ L + M - 1 values (every overlap, the signal padded with M - 1 zeros
69⍝│ at each end), same the L centered on full (as numpy centers them),
70⍝│ valid the L - M + 1 complete overlaps (a kernel longer than the
71⍝│ signal stops the program when it runs); no mode is implicit.
72⍝│ Convolution is y[n] = sum over m of x[n - m] h[m], the kernel
73⍝│ reversed as it slides; correlation y[n] = sum over m of x[n + m]
74⍝│ h[m], not reversed, so correlation is convolution with the kernel
75⍝│ reversed. xetal expand shows the sum each call becomes. Both sides
76⍝│ are notations (MC32), drawn by e:c_onvolveTex<.
77⍝│ takes: notation notation
78⍝│ draws: c_onvolveTex<
79⍝│ uses: parsed
80ᵐc̲onvolve< ← { lhs rhs → "convolve" ʰs̲lide (lhs, rhs) }
81
82⍝│ Cross-correlation, the same call shape (see c_onvolve<); drawn by
83⍝│ e:c_orrelateTex<.
84⍝│ takes: notation notation
85⍝│ draws: c_orrelateTex<
86⍝│ uses: parsed
87ᵐc̲orrelate< ← { lhs rhs → "correlate" ʰs̲lide (lhs, rhs) }
88
89⍝│ The LaTeX of a convolution call, a string: the textbook sum,
90⍝│ y_{n} = \sum_{m} x_{n-m} \, h_{m}, with the mode after it in words.
91⍝│ takes: text text
92⍝│ uses: parsed
93ᵐc̲onvolveTex< ← { lhs rhs → "convolve" ʰs̲lideTex (lhs, rhs) }
94
95⍝│ The LaTeX of a correlation call (x_{n+m}, the kernel not reversed).
96⍝│ takes: text text
97⍝│ uses: parsed
98ᵐc̲orrelateTex< ← { lhs rhs → "correlate" ʰs̲lideTex (lhs, rhs) }
99
100⍝━━ Convolution and correlation
101
102⍝│ The boundary modes.
103modes ← "full" "same" "valid"
104
105⍝│ The expansion of a convolution or correlation call: a block that
106⍝│ measures the signal (L) and the kernel (M), pads the signal with
107⍝│ M - 1 zeros of its own type at each end (full and same), checks the
108⍝│ lengths (valid), then the equation over the free index, computed
109⍝│ as any equation is.
110ʰs̲lide ← { op (lhs, rhs) →
111 (y, n, mode) ← ʰs̲lideLeft lhs
112 (x, h) ← ʰs̲lideRight rhs
113 (gL, gM, gC, gP) ← (⎕G̲ENSYM "L", ⎕G̲ENSYM "M", ⎕G̲ENSYM "c", ⎕G̲ENSYM "p")
114 m ← n ʰo̲therIndex ("m", "j", "q")
115 lines ← " " c̲at gL c̲at " := t_ally " c̲at x c̲at "\n " c̲at gM c̲at " := t_ally " c̲at h c̲at "\n " c̲at gC c̲at " := (" c̲at gM c̲at " - 1) d_iv 2\n " c̲at gP c̲at " := ((" c̲at gM c̲at " - 1) r_eshape 0 * 1 t_ake " c̲at x c̲at ") c_at " c̲at x c̲at " c_at (" c̲at gM c̲at " - 1) r_eshape 0 * 1 t_ake " c̲at x c̲at "\n"
116 check ← ("valid" m̲atch mode) ʰp̲ickText (" _ := { @ -> " c̲at gM c̲at " <= " c̲at gL c̲at " ? @; \"valid-mode\" []S_IGNAL \"valid: the kernel (\" c_at (f_ormat " c̲at gM c̲at ") c_at \") is longer than the signal (\" c_at (f_ormat " c̲at gL c̲at ") c_at \")\" } @\n", "")
117 extent ← ("full" m̲atch mode) ʰp̲ickText (gL c̲at "+" c̲at gM c̲at "-1", ("same" m̲atch mode) ʰp̲ickText (gL, gL c̲at "-" c̲at gM c̲at "+1"))
118 signal ← ("valid" m̲atch mode) ʰp̲ickText (x, gP)
119 shift ← ("full" m̲atch mode) ʰp̲ickText (gM c̲at "-1", ("same" m̲atch mode) ʰp̲ickText (gM c̲at "-1+" c̲at gC, ""))
120 at ← ("convolve" m̲atch op) ʰp̲ickText (n c̲at (ʰp̲lus ("valid" m̲atch mode) ʰp̲ickText (gM c̲at "-1", shift)) c̲at "-" c̲at m, n c̲at (ʰp̲lus ("valid" m̲atch mode) ʰp̲ickText ("", ("full" m̲atch mode) ʰp̲ickText ("", gC))) c̲at "+" c̲at m)
121 eq ← "sum " c̲at m c̲at ":=0.." c̲at gM c̲at "-1 | " c̲at signal c̲at "[" c̲at at c̲at "] * " c̲at h c̲at "[" c̲at m c̲at "]"
122 "({ @ ->\n" c̲at lines c̲at check c̲at " " c̲at ((ʰf̲ree y c̲at "[" c̲at n c̲at "] | " c̲at extent) ʰv̲alue ʰc̲hecked eq) c̲at "\n} @)"
123}
124
125⍝│ The LaTeX of a convolution or correlation call as a string literal:
126⍝│ the result and its index, = , the sum over the kernel's index of the
127⍝│ signal at n - m (convolution) or n + m (correlation) times the
128⍝│ kernel at m, then the mode in words; the sides read as the call is.
129ʰs̲lideTex ← { op (lhs, rhs) →
130 (y, n, mode) ← ʰs̲lideLeft lhs
131 (x, h) ← ʰs̲lideRight rhs
132 m ← n ʰo̲therIndex ("m", "j", "q")
133 sign ← ("convolve" m̲atch op) ʰp̲ickText (" - ", " + ")
134 "\"" c̲at y c̲at "_{" c̲at n c̲at "} = \\\\sum_{" c̲at m c̲at "} " c̲at x c̲at "_{" c̲at n c̲at sign c̲at m c̲at "} \\\\, " c̲at h c̲at "_{" c̲at m c̲at "} \\\\quad \\\\text{(" c̲at mode c̲at ")}\""
135}
136
137⍝│ "+" and t, or "" for an empty t.
138ʰp̲lus ← { t →
139 0 = t̲ally t ? ""
140 "+" c̲at t
141}
142
143⍝│ The left side "y[n] | mode" as (result, index, mode): one index, a
144⍝│ mode the library has.
145ʰs̲lideLeft ← { lhs →
146 l ← "|" ᵖᵃs̲plit lhs
147 _ ← (2 = t̲ally l) ᵖᵃr̲equire ("bad-convolution left", "the result, its index and the mode: \"y[n] | full\"")
148 (y, ix) ← "bad-convolution left" ᵖᵃr̲eference d̲isclose f̲irst l
149 _ ← (1 = t̲ally ix) ᵖᵃr̲equire ("bad-convolution left", "one index: \"y[n] | full\", not " c̲at lhs)
150 mode ← ᵗt̲rim d̲isclose 2 s̲elect l
151 _ ← (0 < t̲ally mode) ᵖᵃr̲equire ("bad-convolution left", "the mode is not implicit: write full, same or valid after |")
152 _ ← ('∨ r̲/ 0 + '{ w → (d̲isclose w) m̲atch mode } e̲ach modes) ᵖᵃr̲equire ("bad-convolution left", "the mode is full, same or valid, not " c̲at mode)
153 (y, d̲isclose f̲irst ix, mode)
154}
155
156⍝│ The right side "x h" as (signal, kernel): two names.
157ʰs̲lideRight ← { rhs →
158 ws ← ᵗw̲ords rhs
159 _ ← (2 = t̲ally ws) ᵖᵃr̲equire ("bad-convolution right", "the signal and the kernel, two names: \"x h\", not " c̲at rhs)
160 _ ← ('∧ r̲/ 1 c̲at '{ w → ᵖᵃn̲ame? d̲isclose w } e̲ach ws) ᵖᵃr̲equire ("bad-convolution right", "the signal and the kernel are names: " c̲at rhs)
161 (d̲isclose f̲irst ws, d̲isclose 2 s̲elect ws)
162}
163
164⍝│ The first of the candidates that is not the free index, as the sum's
165⍝│ index.
166ʰo̲therIndex ← { n (a, b, c) →
167 n̲ot n m̲atch a ? a
168 n̲ot n m̲atch b ? b
169 c
170}
171
172⍝━━ Reading the call
173
174⍝│ The free indices and their extents, from "Y[o,h,w] | O Ho Wo", as
175⍝│ (names, extents), boxed texts; "L[] | " gives none of either.
176ʰf̲ree ← { lhs →
177 l ← "|" ᵖᵃs̲plit lhs
178 _ ← (2 = t̲ally l) ᵖᵃr̲equire ("bad-equation left", "the result, then | and its extents: \"Y[o,h,w] | O Ho Wo\"")
179 head ← d̲isclose f̲irst l
180 _ ← (0 < t̲ally w̲here head m̲ember? "[") ᵖᵃr̲equire ("bad-equation left", "the result names its free indices in brackets: Y[o,h,w], or L[] for a scalar")
181 (_, names) ← "bad-equation left" ᵖᵃr̲eference head
182 extents ← " " ᵖᵃs̲plit d̲isclose f̲irst 1 d̲rop l
183 _ ← ((t̲ally names) = t̲ally extents) ᵖᵃr̲equire ("bad-equation left", "one extent for each free index: " c̲at lhs)
184 (names, extents)
185}
186
187⍝│ The right text, checked: its characters are the grammar's, a bare
188⍝│ sum is wrapped as the term it is, and the reading written back
189⍝│ equals the text with its spaces removed (so no rule dropped a
190⍝│ character); the text to read.
191ʰc̲hecked ← { rhs →
192 t ← ᵗt̲rim rhs
193 _ ← (0 < t̲ally t) ᵖᵃr̲equire ("bad-equation right", "an empty equation")
194 bad ← (n̲ot t m̲ember? alphabet) r̲eplicate t
195 0 < t̲ally bad ? "bad-equation right" ⎕R̲EJECT "not a character of an equation (names, numbers, + - * / ^, parentheses, brackets, a sum's | := and ..): " c̲at (1 t̲ake bad) c̲at " in " c̲at t
196 whole ← ʰw̲hole t
197 back ← ʰp̲lain whole
198 _ ← (back m̲atch ᵖᵃs̲queeze whole) ᵖᵃr̲equire ("bad-equation right", "the reader did not use all of the text: it read " c̲at back c̲at " from " c̲at t)
199 t
200}
201
202⍝│ A right side that is one bare sum, "sum i:=0..n | body", as the term
203⍝│ it is, parenthesized; anything else as written.
204ʰw̲hole ← { t →
205 0 < '+ r̲/ 0 + "|" ᵖᵃt̲op t ? "(" c̲at t c̲at ")"
206 t
207}
208
209⍝━━ The grammar, shared by the three readings
210
211⍝│ Characters of names and numbers.
212nameChars ← "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_:"
213
214⍝│ Every character an equation may hold.
215alphabet ← nameChars c̲at ".+-*/^()[]|,= "
216
217⍝│ The operator words and the functions.
218words ← "sum" "prod" "max" "min" "integral" "scan"
219functions ← "exp" "log" "sqrt" "abs" "sin" "cos" "max" "min"
220
221⍝│ The quadrature rules an integral may be taken by, and the default
222⍝│ option text when a call writes none.
223rules ← "trapezoid" "simpson"
224defaultBy ← "trapezoid 64"
225
226⍝│ The spellings of an infinite bound.
227infinities ← "inf" "-inf" "+inf" "infinity" "-infinity" "oo" "-oo"
228
229⍝│ a when c holds, else b, both already computed: texts or counts (one each: a library's helpers form one binding group, in
230⍝│ which a helper used at two types is not yet generalized).
231ʰp̲ickText ← { c (a, b) →
232 c ? a
233 b
234}
235ʰp̲ickCount ← { c (a, b) →
236 c ? a
237 b
238}
239
240⍝│ What a term is, from its text (trimmed, not empty): "add" (a chain of
241⍝│ + and -, a leading - a negation), "mul" (* and /), "pow" (^), "sum"
242⍝│ (a parenthesized sum), "group" (parentheses), "fn" (a function
243⍝│ applied), "ref" (an array indexed) or "atom" (a name or a number).
244⍝│ One place decides, so the value, the LaTeX and the reprint agree.
245ʰk̲ind ← { t →
246 0 < '+ r̲/ 0 + "+-" ᵖᵃt̲op t ? "add"
247 0 < '+ r̲/ 0 + "*/" ᵖᵃt̲op t ? "mul"
248 0 < '+ r̲/ 0 + "^" ᵖᵃt̲op t ? "pow"
249 (ᵖᵃg̲roup? t) ∧ 0 < '+ r̲/ 0 + "|" ᵖᵃt̲op ᵖᵃi̲nner t ? "sum"
250 ᵖᵃg̲roup? t ? "group"
251 ʰf̲n? t ? "fn"
252 0 < t̲ally w̲here t m̲ember? "[" ? "ref"
253 "atom"
254}
255
256⍝│ Whether t is a function applied: a word, then one parenthesized
257⍝│ group that ends the text (pa:a_pplied?'s shape alone): the fixed
258⍝│ math functions and the program's own are both read this way
259⍝│ (X_eTaL-ML ask E3), told apart only in h:v_alueFn/h:t_exFn.
260ʰf̲n? ← { t → ᵖᵃa̲pplied? t }
261
262⍝│ A function applied, as (name, arguments), the arguments cut at the
263⍝│ top-level commas. The count is checked only for a fixed math
264⍝│ function (its own, not the caller's): a named function is trusted
265⍝│ with however many it is given, since nothing here knows its real
266⍝│ arity -- a wrong count is caught only when the expanded code fails
267⍝│ to compile (X_eTaL-ML ask E3, decided with the user).
268ʰf̲nParts ← { t →
269 (name, args) ← "bad-equation right" ᵖᵃa̲pplied t
270 known ← 0 < '+ r̲/ 0 + '{ f → (d̲isclose f) m̲atch name } e̲ach functions
271 wanted ← (("max" m̲atch name) ∨ ("min" m̲atch name)) ʰp̲ickCount (2, 1)
272 _ ← ((n̲ot known) ∨ (wanted = t̲ally args)) ᵖᵃr̲equire ("bad-equation right", name c̲at " takes " c̲at (f̲ormat wanted) c̲at " argument(s): " c̲at t)
273 (name, args)
274}
275
276⍝│ A parenthesized sum as (words, indices, lows, highs, options, body):
277⍝│ the bindings before the top-level |, each "word i:=low..high" (the
278⍝│ word an operator word), an integral's followed by its by options
279⍝│ (the text after by as written, "" for none).
280ʰs̲umParts ← { t →
281 inner ← ᵖᵃi̲nner t
282 cut ← "|" ᵖᵃt̲op inner
283 _ ← (1 = '+ r̲/ 0 + cut) ᵖᵃr̲equire ("bad-equation right", "a sum has its bindings, then one | and its body: " c̲at t)
284 at ← f̲irst w̲here cut
285 bindings ← "," ᵖᵃs̲plit (at − 1) t̲ake inner
286 body ← ᵗt̲rim at d̲rop inner
287 _ ← (0 < t̲ally body) ᵖᵃr̲equire ("bad-equation right", "a sum needs a body after |: " c̲at t)
288 ds ← '{ b → ʰb̲oxed ʰb̲inding d̲isclose b } m̲ap bindings
289 p̲art ← { k → '{ d → d̲isclose k s̲elect d̲isclose d } m̲ap ds }
290 (p̲art 1, p̲art 2, p̲art 3, p̲art 4, p̲art 5, body)
291}
292
293⍝│ One binding, "word i:=low..high", "integral x:=a..b by rule n" or
294⍝│ "scan t:=lo..hi by seed", as (word, index, low, high, options): the
295⍝│ by options cut off before Parsing reads the range, then checked
296⍝│ (an integral's rule and grid; a scan's seed, any expression of the
297⍝│ caller's values, checked only when it is read as one; a sum has
298⍝│ neither; an integral's bounds are finite).
299ʰb̲inding ← { b →
300 at ← " by " ᵖᵃa̲t b
301 core ← ᵗt̲rim at ʰu̲pTo b
302 opt ← ᵗt̲rim (at, 4) ʰp̲ast b
303 (w, i, lo, hi) ← ("bad-equation right", "an operator word", words) ᵖᵃb̲inding core
304 integral ← "integral" m̲atch w
305 scan ← "scan" m̲atch w
306 _ ← ((integral ∨ scan) ∨ 0 = at) ᵖᵃr̲equire ("bad-equation right", "by names an integral's rule and grid, or a scan's seed; a " c̲at w c̲at " takes none: " c̲at b)
307 _ ← (n̲ot integral ∧ (ʰi̲nfinite? lo) ∨ ʰi̲nfinite? hi) ᵖᵃr̲equire ("bad-equation right", "an improper integral (a bound of inf): write a truncation, 0..20 say, and show the tail is small, or change variables so the bounds are finite: " c̲at b)
308 _ ← ʰo̲ptionsOk (integral, at, opt)
309 (w, i, lo, hi, opt)
310}
311
312⍝│ Whether a bound is written infinite (inf, -inf, infinity, oo).
313ʰi̲nfinite? ← { b → '∨ r̲/ 0 + '{ f → (d̲isclose f) m̲atch b } e̲ach infinities }
314
315⍝│ The by options checked when there are any (at is where by was
316⍝│ found, 0 for none): an integral's rule and grid; a scan's seed is
317⍝│ any expression, read when the scan itself is (h:v_alueScan).
318ʰo̲ptionsOk ← { (integral, at, opt) →
319 0 = at ? 1 = 1
320 n̲ot integral ? 1 = 1
321 ʰo̲ption? opt
322}
323
324⍝│ Whether an integral's by options are a rule the library has and a
325⍝│ whole number of steps (even for simpson); else a refusal.
326ʰo̲ption? ← { opt →
327 ws ← ᵗw̲ords opt
328 _ ← (2 = t̲ally ws) ᵖᵃr̲equire ("bad-equation right", "after by: the rule and the grid, trapezoid 64 or simpson 32, not " c̲at opt)
329 rule ← d̲isclose f̲irst ws
330 n ← d̲isclose 2 s̲elect ws
331 _ ← ('∨ r̲/ 0 + '{ r → (d̲isclose r) m̲atch rule } e̲ach rules) ᵖᵃr̲equire ("bad-equation right", "the rule is trapezoid or simpson, not " c̲at rule)
332 _ ← ((0 < t̲ally n) ∧ '∧ r̲/ n m̲ember? ⎕D) ᵖᵃr̲equire ("bad-equation right", "the grid is a whole number of steps: " c̲at n)
333 k ← f̲irst f̲loor n̲umbers n
334 _ ← (0 < k) ᵖᵃr̲equire ("bad-equation right", "the grid needs at least one step: " c̲at n)
335 _ ← (n̲ot (rule m̲atch "simpson") ∧ 1 = k m̲od 2) ᵖᵃr̲equire ("bad-equation right", "simpson needs an even number of steps, not " c̲at n)
336 1 = 1
337}
338
339⍝│ The rule and the steps of an integral's options ("" for the default).
340ʰr̲uleSteps ← { opt →
341 ws ← ᵗw̲ords ((0 = t̲ally opt) ʰp̲ickText (defaultBy, opt))
342 (d̲isclose f̲irst ws, f̲irst f̲loor n̲umbers d̲isclose 2 s̲elect ws)
343}
344
345⍝│ s before position k (all of s when k is 0), and s after a separator
346⍝│ of length m at position k ("" when k is 0).
347ʰu̲pTo ← { k s →
348 0 = k ? s
349 (k − 1) t̲ake s
350}
351ʰp̲ast ← { (k, m) s →
352 0 = k ? ""
353 ((k + m) − 1) d̲rop s
354}
355
356⍝│ A binding's (word, index, low, high, options), boxed, so a sum's
357⍝│ bindings can be taken apart by position.
358ʰb̲oxed ← { (w, i, lo, hi, o) → (e̲nclose w) c̲at (e̲nclose i) c̲at (e̲nclose lo) c̲at (e̲nclose hi) c̲at e̲nclose o }
359
360⍝│ An atom checked: a name or a number.
361ʰa̲tom ← { t →
362 _ ← ((0 < t̲ally t) ∧ '× r̲/ 0 + t m̲ember? nameChars c̲at ".") ᵖᵃr̲equire ("bad-equation right", "not a name, number, A[i,j], function or (sum ...) in an equation: " c̲at t)
363 t
364}
365
366⍝━━ The value
367
368⍝│ The whole expansion: a block defining the checks, the grid of the
369⍝│ free indices, and the expression's value over it.
370ʰv̲alue ← { (names, extents) t →
371 helpers ← (⎕G̲ENSYM "a_t", ⎕G̲ENSYM "c_heck", ⎕G̲ENSYM "r_ank")
372 (at, chk, rk) ← helpers
373 grid ← ⎕G̲ENSYM "grid"
374 cell ← ⎕G̲ENSYM "g_rid"
375 spans ← '{ e → (e̲nclose "") ʰb̲ound d̲isclose e } m̲ap extents
376 lows ← (t̲ally names) r̲eshape e̲nclose "(0 + "
377 env ← (names, spans, lows, cell, helpers)
378 gridLines ← (0 = t̲ally names) ʰp̲ickText ("", ʰg̲ridLines (grid, cell, spans))
379 atLine ← " " c̲at at c̲at " := { A i -> (1 + i) s_elect r_avel A }\n"
380 ⍝ A value that names no index is a scalar: shaped to the grid, so the
381 ⍝ result has one axis per free index whatever the expression.
382 shaped ← (0 = t̲ally names) ʰp̲ickText ("", grid c̲at " r_eshape ")
383 "({ @ ->\n" c̲at atLine c̲at (ʰc̲hecks (chk, rk)) c̲at gridLines c̲at " " c̲at shaped c̲at "(" c̲at (env ʰv̲alueOf ʰw̲hole t) c̲at ")\n} @)"
384}
385
386⍝│ The lines defining a grid over spans and its cell function (the
387⍝│ coordinates along axis k, shaped like the grid).
388ʰg̲ridLines ← { (grid, cell, spans) →
389 " " c̲at grid c̲at " := " c̲at (" c_at " ʰj̲oinWith spans) c̲at "\n " c̲at cell c̲at " := { k -> " c̲at grid c̲at " r_eshape (o_ffsets k s_elect " c̲at grid c̲at ") 'l_eft t_able ('* r_/ k d_rop " c̲at grid c̲at ") r_eshape 0 }\n"
390}
391
392⍝│ The value of a term in env (the indices in scope, their spans and
393⍝│ lows, the grid's cell function, the helpers), as X_eTaL text.
394ʰv̲alueOf ← { env text →
395 t ← ᵗt̲rim text
396 k ← ʰk̲ind t
397 "add" m̲atch k ? env ʰv̲alueChain ("+-", t)
398 "mul" m̲atch k ? env ʰv̲alueChain ("*/", t)
399 "pow" m̲atch k ? env ʰv̲aluePow t
400 "sum" m̲atch k ? env ʰv̲alueSum t
401 "group" m̲atch k ? "(" c̲at (env ʰv̲alueOf ᵖᵃi̲nner t) c̲at ")"
402 "fn" m̲atch k ? env ʰv̲alueFn t
403 "ref" m̲atch k ? env ʰv̲alueRef t
404 env ʰv̲alueAtom ʰa̲tom t
405}
406
407⍝│ A chain folded left: ((a + b) - c); a leading minus is 0 - a.
408ʰv̲alueChain ← { env (ops, t) →
409 (parts, os, neg) ← ("bad-equation right", ops) ᵖᵃp̲arts t
410 first ← env ʰv̲alueOf d̲isclose f̲irst parts
411 acc ← neg ʰp̲ickText ("(0 - " c̲at first c̲at ")", first)
412 env ʰv̲alueFold (acc, os, 1 d̲rop parts)
413}
414
415⍝│ The left fold of a chain: acc, then each operator with the next part.
416ʰv̲alueFold ← { env (acc, os, parts) →
417 0 = t̲ally os ? acc
418 next ← "(" c̲at acc c̲at " " c̲at (1 t̲ake os) c̲at " " c̲at (env ʰv̲alueOf d̲isclose f̲irst parts) c̲at ")"
419 env ʰv̲alueFold (next, 1 d̲rop os, 1 d̲rop parts)
420}
421
422⍝│ a ^ b, right to left: the text cut at its first top-level ^.
423ʰv̲aluePow ← { env t →
424 i ← f̲irst w̲here "^" ᵖᵃt̲op t
425 "(" c̲at (env ʰv̲alueOf (i − 1) t̲ake t) c̲at " ^ " c̲at (env ʰv̲alueOf i d̲rop t) c̲at ")"
426}
427
428⍝│ A parenthesized sum: a block with its own grid over the indices in
429⍝│ scope and then its own, the body on that grid, and one reduction per
430⍝│ binding (innermost first), leaving an array over the indices in
431⍝│ scope. A scan is not a reduction (its term may use the one before,
432⍝│ X_eTaL-ML ask E2) and is handled on its own, h:v_alueScan, before
433⍝│ any of this -- it must be the term's only binding. Outside a scan,
434⍝│ prev is refused wherever it is written: the word is reserved for
435⍝│ the term a scan folds into the one before it.
436ʰv̲alueSum ← { (names, spans, lows, cell, helpers) t →
437 (ws, ns, ls, hs, os, body) ← ʰs̲umParts t
438 isScan ← 0 < '+ r̲/ 0 + '{ w → (d̲isclose w) m̲atch "scan" } e̲ach ws
439 _ ← ((n̲ot isScan) ∨ (1 = t̲ally ws)) ᵖᵃr̲equire ("bad-equation right", "a scan must be the only binding of its term (no sum, prod, max, min or integral alongside it): " c̲at t)
440 isScan ? ʰv̲alueScan ((names, spans, lows, cell, helpers), d̲isclose f̲irst ns, d̲isclose f̲irst ls, d̲isclose f̲irst hs, d̲isclose f̲irst os, body)
441 _ ← (n̲ot ʰh̲asPrev? body) ᵖᵃr̲equire ("bad-equation right", "prev names the term before inside a scan; it cannot be used here: " c̲at t)
442 n ← t̲ally names
443 _ ← ((t̲ally ns) = '+ r̲/ 0 + r̲avel (names c̲at ns) 'm̲atch t̲able ns) ᵖᵃr̲equire ("bad-equation right", "an index is bound once: " c̲at (", " ʰj̲oinWith (names c̲at ns)))
444 qs ← '{ k → names ʰq̲uadrature (d̲isclose k s̲elect ws, d̲isclose k s̲elect ls, d̲isclose k s̲elect hs, d̲isclose k s̲elect os) } m̲ap r̲ange t̲ally ns
445 q̲ ← { k j → d̲isclose j s̲elect d̲isclose k s̲elect qs }
446 own ← '{ k → k q̲ 1 } m̲ap r̲ange t̲ally ns
447 lows2 ← '{ k → k q̲ 2 } m̲ap r̲ange t̲ally ns
448 grid ← ⎕G̲ENSYM "grid"
449 cell2 ← ⎕G̲ENSYM "g_rid"
450 env ← (names c̲at ns, spans c̲at own, lows c̲at lows2, cell2, helpers)
451 reds ← "" ᵗj̲oin '{ k → (ʰr̲educer d̲isclose k s̲elect ws) c̲at " r_/_" c̲at (f̲ormat n + k) c̲at " " } m̲ap r̲ange t̲ally ns
452 weighted ← "" ᵗj̲oin '{ k → ʰw̲eighted (k q̲ 4, cell2, n + k) } m̲ap r̲ange t̲ally ns
453 none ← 0 = t̲ally spans c̲at own
454 lines ← ("" ᵗj̲oin '{ k → k q̲ 3 } m̲ap r̲ange t̲ally ns) c̲at none ʰp̲ickText ("", ʰg̲ridLines (grid, cell2, spans c̲at own))
455 shaped ← none ʰp̲ickText ("", grid c̲at " r_eshape ")
456 "({ @ ->\n" c̲at lines c̲at " " c̲at reds c̲at shaped c̲at weighted c̲at "(" c̲at (env ʰv̲alueOf body) c̲at ")\n} @)"
457}
458
459⍝│ The length of the leading run of name characters in t (0 if t does
460⍝│ not start with one): how h:r_enamed and h:h_asPrev? find a whole
461⍝│ word instead of matching part of a longer name.
462ʰw̲ordLen ← { t →
463 0 = t̲ally t ? 0
464 n̲ot (f̲irst t m̲ember? nameChars) ? 0
465 1 + ʰw̲ordLen 1 d̲rop t
466}
467
468⍝│ t with every whole-word occurrence of from replaced by to, anything
469⍝│ else untouched: how a scan's index and prev become plain generated
470⍝│ names before the body is translated like any other expression (its
471⍝│ own grammar has no notion of either, so they are never looked up
472⍝│ through the grid env the other bindings use).
473ʰr̲enamed ← { (from, to) t →
474 0 = t̲ally t ? t
475 n̲ot (f̲irst t m̲ember? nameChars) ? (1 t̲ake t) c̲at (from, to) ʰr̲enamed 1 d̲rop t
476 k ← ʰw̲ordLen t
477 word ← k t̲ake t
478 piece ← ({ @ → (word m̲atch from) ? to◆ word } @)
479 piece c̲at (from, to) ʰr̲enamed k d̲rop t
480}
481
482⍝│ Whether prev appears as a whole word anywhere in t: the word a
483⍝│ scan's own body may use (its term before), refused everywhere else.
484ʰh̲asPrev? ← { t →
485 0 = t̲ally t ? 1 = 0
486 n̲ot (f̲irst t m̲ember? nameChars) ? ʰh̲asPrev? 1 d̲rop t
487 k ← ʰw̲ordLen t
488 ((k t̲ake t) m̲atch "prev") ? 1 = 1
489 ʰh̲asPrev? k d̲rop t
490}
491
492⍝│ A scan's value: a genuine fold, not a reduction -- the array
493⍝│ machinery's reduce is a right fold (B6), only the same as a running
494⍝│ left-to-right accumulation when the combining step is associative,
495⍝│ which a scan's body need not be. Built instead from p_ower: one
496⍝│ state-threading step function, (t, prev) to (t's successor, the
497⍝│ body at that successor), applied once per point of the range,
498⍝│ starting one step before the low end so the first real application
499⍝│ lands there. prev starts at the seed (by, X_eTaL-ML ask E2); a
500⍝│ scan with no seed and a body that never names prev folds in a seed
501⍝│ of 0 harmlessly, since it is never read. The index and prev are
502⍝│ substituted into the body's own translation (not its text: that
503⍝│ would be reparsed as if it were the equation's grammar, which it
504⍝│ is not) by name, so a scan's free indices, references and nested
505⍝│ terms still translate through the ordinary env.
506ʰv̲alueScan ← { (env, index, lo, hi, seed, body) →
507 (names, _, _, _, _) ← env
508 loCode ← names ʰb̲ound lo
509 hiCode ← names ʰb̲ound hi
510 _ ← ((0 < t̲ally seed) ∨ (n̲ot (ʰh̲asPrev? body))) ᵖᵃr̲equire ("bad-equation right", "a scan whose body uses prev needs a seed: scan " c̲at index c̲at ":=" c̲at lo c̲at ".." c̲at hi c̲at " by seed | " c̲at body)
511 seedCode ← (0 = t̲ally seed) ʰp̲ickText ("0", names ʰb̲ound seed)
512 rawBody ← env ʰv̲alueOf body
513 (gStep, gT, gAcc, gNext) ← (⎕G̲ENSYM "step", ⎕G̲ENSYM "t", ⎕G̲ENSYM "acc", ⎕G̲ENSYM "t")
514 stepBody ← (index, gNext) ʰr̲enamed (("prev", gAcc) ʰr̲enamed rawBody)
515 "(({ @ ->\n " c̲at gStep c̲at " := ({ @ -> ((" c̲at hiCode c̲at ") >= (" c̲at loCode c̲at ")) ? 1; 0 - 1 } @)\n (_, " c̲at gAcc c̲at ") := (1 + a_bs ((" c̲at hiCode c̲at ") - (" c̲at loCode c̲at "))) '{ (" c̲at gT c̲at ", " c̲at gAcc c̲at ") ->\n " c̲at gNext c̲at " := " c̲at gT c̲at " + " c̲at gStep c̲at "\n (" c̲at gNext c̲at ", " c̲at stepBody c̲at ")\n } p_ower ((" c̲at loCode c̲at ") - " c̲at gStep c̲at ", " c̲at seedCode c̲at ")\n " c̲at gAcc c̲at "\n} @))"
516}
517
518⍝│ A binding's span, coordinate prefix, defining lines and weights
519⍝│ name, as texts: a sum's span is its range's length, checked at run
520⍝│ time (low and high are the caller's values, not known until then):
521⍝│ a negative length -- the range runs high..low, backwards -- signals
522⍝│ error[bad-equation] naming the word and the range as written,
523⍝│ rather than falling through to the array machinery's own count
524⍝│ error (X_eTaL-ML ask E1); its coordinate is its low plus the cell,
525⍝│ no lines, no weights; an integral's span is its grid's n + 1
526⍝│ points, its coordinate a + h * the cell, its lines define a, b, h
527⍝│ and the weights (fresh names, so the body may name any of a, b, h
528⍝│ or w), the weights holding the rule's and the step.
529ʰq̲uadrature ← { names (w, lo, hi, opt) →
530 n̲ot "integral" m̲atch w ? (e̲nclose "({ v -> (0 <= v) ? v; \"bad-equation\" []S_IGNAL \"" c̲at w c̲at "'s range runs low..high: " c̲at lo c̲at ".." c̲at hi c̲at "\" } (1 + " c̲at (names ʰb̲ound hi) c̲at " - " c̲at (names ʰb̲ound lo) c̲at "))") c̲at (e̲nclose "(" c̲at (names ʰb̲ound lo) c̲at " + ") c̲at (e̲nclose "") c̲at e̲nclose ""
531 (rule, k) ← ʰr̲uleSteps opt
532 (a, b, h, ws) ← (⎕G̲ENSYM "a", ⎕G̲ENSYM "b", ⎕G̲ENSYM "h", ⎕G̲ENSYM "w")
533 lines ← " " c̲at a c̲at " := f_loat (" c̲at (names ʰb̲ound lo) c̲at ")\n " c̲at b c̲at " := f_loat (" c̲at (names ʰb̲ound hi) c̲at ")\n " c̲at h c̲at " := (" c̲at b c̲at " - " c̲at a c̲at ") / " c̲at (f̲ormat k) c̲at ".0\n " c̲at ws c̲at " := " c̲at h c̲at " * " c̲at (rule ʰw̲eights k) c̲at "\n"
534 (e̲nclose "(" c̲at (f̲ormat k + 1) c̲at ")") c̲at (e̲nclose "(" c̲at a c̲at " + " c̲at h c̲at " * f_loat ") c̲at (e̲nclose lines) c̲at e̲nclose ws
535}
536
537⍝│ The rule's weights over k steps (k + 1 points), as code: trapezoid
538⍝│ 1/2, 1, ..., 1, 1/2; simpson (1, 4, 2, 4, ..., 4, 1) / 3.
539ʰw̲eights ← { rule k →
540 rule m̲atch "simpson" ? "(1.0 c_at (" c̲at (f̲ormat k − 1) c̲at " r_eshape 4.0 2.0) c_at 1.0) / 3.0"
541 "0.5 c_at (" c̲at (f̲ormat k − 1) c̲at " r_eshape 1.0) c_at 0.5"
542}
543
544⍝│ The factor an integral's binding puts before the body: its weights
545⍝│ laid over the grid along its axis; "" for a sum.
546ʰw̲eighted ← { (ws, cell, axis) →
547 0 = t̲ally ws ? ""
548 "((1 + " c̲at cell c̲at " " c̲at (f̲ormat axis) c̲at ") s_elect " c̲at ws c̲at ") * "
549}
550
551⍝│ The reduction an operator word stands for.
552ʰr̲educer ← { w →
553 "sum" m̲atch w ? "'+"
554 "prod" m̲atch w ? "'*"
555 "max" m̲atch w ? "'m_ax"
556 "integral" m̲atch w ? "'+"
557 "'m_in"
558}
559
560⍝│ A bound or extent: an expression of the caller's values, with no
561⍝│ index in scope; one that names an index is refused.
562ʰb̲ound ← { names t →
563 used ← '{ w → 0 < '+ r̲/ 0 + '{ n → (d̲isclose n) m̲atch d̲isclose w } e̲ach names } e̲ach ᵗw̲ords ʰs̲paced t
564 _ ← (0 = '+ r̲/ 0 + used) ᵖᵃr̲equire ("bad-equation right", "a bound or extent cannot depend on an index: " c̲at t)
565 (e̲nclose "", e̲nclose "", e̲nclose "", "", ("", "", "")) ʰv̲alueOf t
566}
567
568⍝│ t with its operators and brackets spaced out, so its words are its names.
569ʰs̲paced ← { t → "" ᵗj̲oin '{ ch → (ch m̲ember? "+-*/^()[],") ? " "◆ ch } m̲ap t }
570
571⍝│ A function applied to its arguments' values: the fixed math
572⍝│ functions by their own rule, any other name as the caller's own
573⍝│ u: function, applied to however many arguments it was given
574⍝│ (X_eTaL-ML ask E3) -- u:name(args), not a quoted call, so a name
575⍝│ that is not a function, or not one of this arity, is the expanded
576⍝│ code's own compile error, naming the equation's call.
577ʰv̲alueFn ← { env t →
578 (name, args) ← ʰf̲nParts t
579 vs ← '{ a → env ʰv̲alueOf d̲isclose a } m̲ap args
580 a ← d̲isclose f̲irst vs
581 "sqrt" m̲atch name ? "(" c̲at a c̲at " ^ 0.5)"
582 "exp" m̲atch name ? "(e_xp " c̲at a c̲at ")"
583 "log" m̲atch name ? "(l_og " c̲at a c̲at ")"
584 "abs" m̲atch name ? "(a_bs " c̲at a c̲at ")"
585 "sin" m̲atch name ? "(s_in " c̲at a c̲at ")"
586 "cos" m̲atch name ? "(c_os " c̲at a c̲at ")"
587 (("max" m̲atch name) ∨ ("min" m̲atch name)) ? "(" c̲at a c̲at (("max" m̲atch name) ʰp̲ickText (" m_ax ", " m_in ")) c̲at (d̲isclose 2 s̲elect vs) c̲at ")"
588 "(u:" c̲at name c̲at "(" c̲at (", " ᵗj̲oin vs) c̲at "))"
589}
590
591⍝│ A[e1,...,en] as a gather from A's ravel, the index by Horner's rule
592⍝│ over A's shape (0-origin, as the equation writes it); A is checked
593⍝│ to have n axes, and each index to lie within its axis.
594ʰv̲alueRef ← { (names, spans, lows, cell, (at, chk, rk)) t →
595 (name, ix) ← "bad-equation right" ᵖᵃr̲eference t
596 inner ← (names, spans, lows, cell, (at, chk, rk)) ʰh̲orner (name, ix, t̲ally ix)
597 checked ← "(" c̲at rk c̲at " (" c̲at name c̲at ", \"" c̲at name c̲at "\", " c̲at (f̲ormat t̲ally ix) c̲at ", \"" c̲at t c̲at "\"))"
598 "\n (" c̲at checked c̲at " " c̲at at c̲at " (" c̲at inner c̲at "))"
599}
600
601⍝│ The ravel position of A[e1,...,ek] by Horner's rule: ek + (k-th
602⍝│ extent of A) * (the same for e1 ... e(k-1)), down to e1; each ek
603⍝│ passes through the bounds check.
604ʰh̲orner ← { (names, spans, lows, cell, (at, chk, rk)) (name, ix, k) →
605 env ← (names, spans, lows, cell, (at, chk, rk))
606 written ← ᵗt̲rim d̲isclose k s̲elect ix
607 e ← "\n ((" c̲at name c̲at ", \"" c̲at name c̲at "\", " c̲at (f̲ormat k) c̲at ", \"" c̲at written c̲at "\") " c̲at chk c̲at " " c̲at (env ʰv̲alueOf written) c̲at ")"
608 k = 1 ? e
609 "(" c̲at e c̲at " + (" c̲at (f̲ormat k) c̲at " s_elect s_hape " c̲at name c̲at ") * " c̲at (env ʰh̲orner (name, ix, k − 1)) c̲at ")"
610}
611
612⍝│ An index in scope as its coordinates on the grid (its low added),
613⍝│ anything else as written: the caller's name or a number.
614ʰv̲alueAtom ← { (names, _, lows, cell, _) t →
615 hit ← w̲here '{ n → (d̲isclose n) m̲atch t } e̲ach names
616 0 = t̲ally hit ? t
617 k ← f̲irst hit
618 (d̲isclose k s̲elect lows) c̲at cell c̲at " " c̲at (f̲ormat k) c̲at ")"
619}
620
621⍝│ The two run-time checks the expansion defines: an index within its
622⍝│ axis (0 to the extent less one), and a reference with as many
623⍝│ indices as its array has axes; each names the array, the axis and
624⍝│ the expression as written, and gives its argument back when it holds.
625ʰc̲hecks ← { (chk, rk) →
626 c ← " " c̲at chk c̲at " := { (A, name, k, from) e ->\n n := k s_elect s_hape A\n bad := w_here n_ot r_avel (0 <= e) & e < n\n 0 = t_ally bad ? e\n \"index\" []S_IGNAL name c_at \" axis \" c_at (f_ormat k) c_at \": index \" c_at (f_ormat (f_irst bad) s_elect r_avel e) c_at \" is outside 0..\" c_at (f_ormat n - 1) c_at \" (from \" c_at from c_at \")\"\n }\n"
627 r ← " " c̲at rk c̲at " := { (A, name, q, ref) ->\n (t_ally s_hape A) = q ? A\n \"rank\" []S_IGNAL ref c_at \" indexes \" c_at (f_ormat q) c_at \" axes, but \" c_at name c_at \" has rank \" c_at f_ormat t_ally s_hape A\n }\n"
628 c c̲at r
629}
630
631⍝━━ The same call as LaTeX
632
633⍝│ The LaTeX text of the call (no quotes): the result as written (L for
634⍝│ a scalar), = and the expression; a bare sum without the parentheses
635⍝│ the reader gave it.
636ʰt̲ex ← { lhs rhs →
637 (names, _) ← ʰf̲ree lhs
638 head ← ᵗt̲rim d̲isclose f̲irst "|" ᵖᵃs̲plit lhs
639 name ← ((f̲irst w̲here head m̲ember? "[") − 1) t̲ake head
640 sub ← (0 = t̲ally names) ʰp̲ickText ("", "_{" c̲at ("," ᵗj̲oin names) c̲at "}")
641 (ʰg̲reek name) c̲at sub c̲at " = " c̲at ʰt̲exBody ᵗt̲rim rhs
642}
643
644⍝│ The right side as LaTeX: a bare sum without the parentheses the
645⍝│ reader gives it, anything else as a term.
646ʰt̲exBody ← { t →
647 0 < '+ r̲/ 0 + "|" ᵖᵃt̲op t ? ("", "") ʰt̲exSum t
648 ʰt̲exOf ʰw̲hole t
649}
650
651⍝│ A term as LaTeX.
652ʰt̲exOf ← { text →
653 t ← ᵗt̲rim text
654 k ← ʰk̲ind t
655 "add" m̲atch k ? "+-" ʰt̲exChain t
656 "mul" m̲atch k ? "*/" ʰt̲exChain t
657 "pow" m̲atch k ? ʰt̲exPow t
658 "sum" m̲atch k ? ("\\\\left(", "\\\\right)") ʰt̲exSum ᵖᵃi̲nner t
659 "group" m̲atch k ? "\\\\left(" c̲at (ʰt̲exOf ᵖᵃi̲nner t) c̲at "\\\\right)"
660 "fn" m̲atch k ? ʰt̲exFn t
661 "ref" m̲atch k ? ʰt̲exRef t
662 ʰg̲reek ʰa̲tom t
663}
664
665⍝│ A chain: a + b - c; a \, b for a product; \frac{a}{b} for a quotient.
666ʰt̲exChain ← { ops t →
667 (parts, os, neg) ← ("bad-equation right", ops) ᵖᵃp̲arts t
668 p1 ← d̲isclose f̲irst parts
669 first ← ("/" m̲atch 1 t̲ake os c̲at " ") ʰp̲ickText (ʰt̲exBare p1, ʰt̲exOf p1)
670 acc ← neg ʰp̲ickText ("-" c̲at first, first)
671 ʰt̲exFold (acc, os, 1 d̲rop parts)
672}
673
674ʰt̲exFold ← { (acc, os, parts) →
675 0 = t̲ally os ? acc
676 op ← 1 t̲ake os
677 p ← d̲isclose f̲irst parts
678 next ← ("/" m̲atch op) ʰp̲ickText (ʰt̲exBare p, ʰt̲exOf p)
679 ʰt̲exFold (ʰt̲exJoin (acc, op, next), 1 d̲rop os, 1 d̲rop parts)
680}
681
682⍝│ A term without the parentheses it was written in, where what holds
683⍝│ it already sets it apart: the numerator or denominator of \frac, the
684⍝│ argument of \sqrt.
685ʰt̲exBare ← { text →
686 t ← ᵗt̲rim text
687 k ← ʰk̲ind t
688 "sum" m̲atch k ? ("", "") ʰt̲exSum ᵖᵃi̲nner t
689 "group" m̲atch k ? ʰt̲exOf ᵖᵃi̲nner t
690 ʰt̲exOf t
691}
692
693⍝│ Two operands joined by an operator: \frac for /, a thin space for *.
694ʰt̲exJoin ← { (acc, op, next) →
695 "/" m̲atch op ? "\\\\frac{" c̲at acc c̲at "}{" c̲at next c̲at "}"
696 "*" m̲atch op ? acc c̲at " \\\\, " c̲at next
697 acc c̲at " " c̲at op c̲at " " c̲at next
698}
699
700ʰt̲exPow ← { t →
701 i ← f̲irst w̲here "^" ᵖᵃt̲op t
702 (ʰt̲exOf (i − 1) t̲ake t) c̲at "^{" c̲at (ʰt̲exOf i d̲rop t) c̲at "}"
703}
704
705⍝│ A sum's bindings as \sum_{i=low}^{high} (the operator word's symbol),
706⍝│ then its body, wrapped as asked.
707ʰt̲exSum ← { (open, close) inner →
708 (ws, ns, ls, hs, _, body) ← ʰs̲umParts "(" c̲at inner c̲at ")"
709 o̲ne ← { k → (ʰs̲ymbol d̲isclose k s̲elect ws) c̲at "_{" c̲at (ʰt̲exIndex (d̲isclose k s̲elect ws, d̲isclose k s̲elect ns)) c̲at (ʰt̲exOf d̲isclose k s̲elect ls) c̲at "}^{" c̲at (ʰt̲exOf d̲isclose k s̲elect hs) c̲at "} " }
710 d̲ ← { k → ("integral" m̲atch d̲isclose k s̲elect ws) ʰp̲ickText (" \\\\, d" c̲at (ʰg̲reek d̲isclose k s̲elect ns), "") }
711 open c̲at ("" ᵗj̲oin 'o̲ne m̲ap r̲ange t̲ally ns) c̲at (ʰt̲exOf body) c̲at ("" ᵗj̲oin 'd̲ m̲ap r̲ev r̲ange t̲ally ns) c̲at close
712}
713
714⍝│ A sum's index and = before its low; an integral's lower bound stands
715⍝│ alone (\int_{a}^{b}).
716ʰt̲exIndex ← { (w, i) →
717 "integral" m̲atch w ? ""
718 i c̲at "="
719}
720
721⍝│ A Greek letter's name as its LaTeX command (a capital's too: Phi,
722⍝│ Sigma); any other name as is.
723ʰg̲reek ← { v →
724 '∨ r̲/ 0 + '{ w → (d̲isclose w) m̲atch v } e̲ach ᵗw̲ords greek ? "\\\\" c̲at v
725 v
726}
727greek ← "alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu nu xi pi rho sigma tau upsilon phi chi psi omega Gamma Delta Theta Lambda Xi Pi Sigma Upsilon Phi Psi Omega"
728
729⍝│ The symbol of an operator word.
730ʰs̲ymbol ← { w →
731 "sum" m̲atch w ? "\\\\sum"
732 "prod" m̲atch w ? "\\\\prod"
733 "max" m̲atch w ? "\\\\max"
734 "integral" m̲atch w ? "\\\\int"
735 "scan" m̲atch w ? "\\\\operatorname{scan}"
736 "\\\\min"
737}
738
739⍝│ A function applied: \exp(x), \log(x), \sqrt{x}, \lvert x \rvert, \max(a, b).
740ʰt̲exFn ← { t →
741 (name, args) ← ʰf̲nParts t
742 as ← '{ a → ʰt̲exOf d̲isclose a } m̲ap args
743 a ← d̲isclose f̲irst as
744 known ← 0 < '+ r̲/ 0 + '{ f → (d̲isclose f) m̲atch name } e̲ach functions
745 "sqrt" m̲atch name ? "\\\\sqrt{" c̲at (ʰt̲exBare d̲isclose f̲irst args) c̲at "}"
746 "abs" m̲atch name ? "\\\\lvert " c̲at a c̲at " \\\\rvert"
747 known ? "\\\\" c̲at name c̲at "(" c̲at (", " ᵗj̲oin as) c̲at ")"
748 "\\\\operatorname{" c̲at name c̲at "}(" c̲at (", " ᵗj̲oin as) c̲at ")"
749}
750
751⍝│ A reference as a subscript: A_{i,j}, the indices as written without
752⍝│ spaces, a product among them as a thin space.
753ʰt̲exRef ← { t →
754 (name, ix) ← "bad-equation right" ᵖᵃr̲eference t
755 name c̲at "_{" c̲at ("," ᵗj̲oin '{ i → ʰs̲ubscript d̲isclose i } m̲ap ix) c̲at "}"
756}
757
758ʰs̲ubscript ← { t → "" ᵗj̲oin '{ ch → (ch m̲ember? "*") ? "\\\\,"◆ (ch m̲ember? " ") ? ""◆ ch } m̲ap t }
759
760⍝━━ The reading written back
761
762⍝│ A term as it was read, with no spaces: the same text it came from,
763⍝│ or a rule dropped something.
764ʰp̲lain ← { text →
765 t ← ᵗt̲rim text
766 k ← ʰk̲ind t
767 "add" m̲atch k ? "+-" ʰp̲lainChain t
768 "mul" m̲atch k ? "*/" ʰp̲lainChain t
769 "pow" m̲atch k ? ʰp̲lainPow t
770 "sum" m̲atch k ? ʰp̲lainSum t
771 "group" m̲atch k ? "(" c̲at (ʰp̲lain ᵖᵃi̲nner t) c̲at ")"
772 "fn" m̲atch k ? ʰp̲lainFn t
773 "ref" m̲atch k ? ʰp̲lainRef t
774 ʰa̲tom t
775}
776
777ʰp̲lainChain ← { ops t →
778 (parts, os, neg) ← ("bad-equation right", ops) ᵖᵃp̲arts t
779 first ← ʰp̲lain d̲isclose f̲irst parts
780 acc ← neg ʰp̲ickText ("-" c̲at first, first)
781 ʰp̲lainFold (acc, os, 1 d̲rop parts)
782}
783
784ʰp̲lainFold ← { (acc, os, parts) →
785 0 = t̲ally os ? acc
786 ʰp̲lainFold (acc c̲at (1 t̲ake os) c̲at (ʰp̲lain d̲isclose f̲irst parts), 1 d̲rop os, 1 d̲rop parts)
787}
788
789ʰp̲lainPow ← { t →
790 i ← f̲irst w̲here "^" ᵖᵃt̲op t
791 (ʰp̲lain (i − 1) t̲ake t) c̲at "^" c̲at ʰp̲lain i d̲rop t
792}
793
794ʰp̲lainSum ← { t →
795 (ws, ns, ls, hs, os, body) ← ʰs̲umParts t
796 o̲ne ← { k → (d̲isclose k s̲elect ws) c̲at (d̲isclose k s̲elect ns) c̲at ":=" c̲at (ʰp̲lain d̲isclose k s̲elect ls) c̲at ".." c̲at (ʰp̲lain d̲isclose k s̲elect hs) c̲at ʰp̲lainBy d̲isclose k s̲elect os }
797 "(" c̲at ("," ᵗj̲oin 'o̲ne m̲ap r̲ange t̲ally ns) c̲at "|" c̲at (ʰp̲lain body) c̲at ")"
798}
799
800⍝│ An integral's by options as written, squeezed; "" for none.
801ʰp̲lainBy ← { opt →
802 0 = t̲ally opt ? ""
803 "by" c̲at ᵖᵃs̲queeze opt
804}
805
806ʰp̲lainFn ← { t →
807 (name, args) ← ʰf̲nParts t
808 name c̲at "(" c̲at ("," ᵗj̲oin '{ a → ʰp̲lain d̲isclose a } m̲ap args) c̲at ")"
809}
810
811ʰp̲lainRef ← { t →
812 (name, ix) ← "bad-equation right" ᵖᵃr̲eference t
813 name c̲at "[" c̲at ("," ᵗj̲oin '{ i → ʰp̲lain d̲isclose i } m̲ap ix) c̲at "]"
814}
815
816⍝━━ Text helpers
817
818⍝│ The boxed texts b joined by sep.
819ʰj̲oinWith ← { sep b → sep ᵗj̲oin b }