sourcedemos/stencil-macros/Stencil.xtlm
1⍝# Stencils written as pictures: a macro library. A kernel is written
2⍝# as its numbers, row by row (3 x 3, 5 x 5, ...); when the program is
3⍝# expanded, the macro writes the arithmetic the kernel stands for, one
4⍝# term per number that is not 0: the array moved by that number's
5⍝# offset from the center (a rotation, so the edges wrap) times the
6⍝# number. A 0 writes nothing and a 1 writes no multiply, so the code
7⍝# does exactly the work the kernel asks for.
8
9⍝## Stencils
10
11⍝# The kernel on the left applied to the array named on the right:
12⍝# each cell becomes the sum of its neighbors times the kernel's
13⍝# numbers (the kernel's center on the cell). The kernel is text, its
14⍝# rows apart by two spaces for the reader; the macro needs only that
15⍝# there are 1, 9, 25, ... numbers.
16⍝# >> "s:" u_se< "Stencil"
17⍝# >> h := 3 3 r_eshape 0 0 0 0 1 0 0 0 0
18⍝# >> "0 1 0 1 -4 1 0 1 0" s:s_tencil< "h"
19⍝# 0 1 0
20⍝# 1 -4 1
21⍝# 0 1 0
22ᵐs̲tencil< ← { kernel name →
23 w ← n̲umbers kernel
24 n ← t̲ally w
25 k ← n ʰs̲ide 1
26 n̲ot n = k × k ? "bad-macro-argument left" ⎕R̲EJECT "s:s_tencil< takes a square kernel: 1, 9, 25, ... numbers"
27 c ← (k − 1) d̲iv 2
28 i ← (r̲ange n) − 1
29 cells ← r̲avel o̲\ (3 c̲at n) r̲eshape w c̲at (f̲loat (i d̲iv k) − c) c̲at f̲loat (i m̲od k) − c
30 t ← cells ʰt̲erms name
31 0 = t̲ally t ? "(0 * " c̲at name c̲at ")"
32 "(" c̲at t c̲at ")"
33}
34
35⍝ The side of a square of n cells: the first odd k with k * k >= n.
36ʰs̲ide ← { n k → n ≤ k × k ? k◆ n ʰs̲ide k + 2 }
37
38⍝ The terms of the cells (weight, row offset, column offset, then the
39⍝ next cell's), joined by +; a weight of 0 writes nothing.
40ʰt̲erms ← { cells name →
41 0 = t̲ally cells ? ""
42 rest ← (3 d̲rop cells) ʰt̲erms name
43 w ← f̲irst cells
44 w = 0.0 ? rest
45 t ← (3 t̲ake cells) ʰt̲erm name
46 0 = t̲ally rest ? t
47 t c̲at " + " c̲at rest
48}
49
50⍝ One cell's term: the array moved by the cell's offsets, times its
51⍝ weight (no multiply for 1, a negation for -1). Every term is in
52⍝ parentheses: X_eTaL reads right to left, so a + b - c * d would not
53⍝ mean what the kernel does.
54ʰt̲erm ← { cell name →
55 w ← f̲irst cell
56 b ← (f̲loor 2 s̲elect cell) ʰr̲ows (f̲loor 3 s̲elect cell) ʰc̲ols name
57 w = 1.0 ? b
58 w = -1.0 ? "(n_eg " c̲at b c̲at ")"
59 "(" c̲at (ʰn̲um w) c̲at " * " c̲at b c̲at ")"
60}
61
62⍝ The array moved d columns: the cell d to the right lands here.
63ʰc̲ols ← { d name → d = 0 ? name◆ "(" c̲at (f̲ormat d) c̲at " o_-_2 " c̲at name c̲at ")" }
64
65⍝ The text moved d rows: the cell d below lands here.
66ʰr̲ows ← { d text → d = 0 ? text◆ "(" c̲at (f̲ormat d) c̲at " o_-_1 " c̲at text c̲at ")" }
67
68⍝ A weight as written: 2 for 2.0, 0.25 as it is.
69ʰn̲um ← { w → w = f̲loat f̲loor w ? f̲ormat f̲loor w◆ f̲ormat w }