macro librarydemos/stencil-macros/Stencil.xtlm
Stencils written as pictures: a macro library. A kernel is written as its numbers, row by row (3 x 3, 5 x 5, ...); when the program is expanded, the macro writes the arithmetic the kernel stands for, one term per number that is not 0: the array moved by that number's offset from the center (a rotation, so the edges wrap) times the number. A 0 writes nothing and a 1 writes no multiply, so the code does exactly the work the kernel asks for.
Stencils
ᵐs̲tencil< : Char -> Char -> Char
The kernel on the left applied to the array named on the right: each cell becomes the sum of its neighbors times the kernel's numbers (the kernel's center on the cell). The kernel is text, its rows apart by two spaces for the reader; the macro needs only that there are 1, 9, 25, ... numbers.
ˢ⁼u̲se< "Stencil"
h ← 3 3 r̲eshape 0 0 0 0 1 0 0 0 0
"0 1 0 1 -4 1 0 1 0" ˢs̲tencil< "h" 0 1 0 1 -4 1 0 1 0
ᵐs̲tencil< ← { kernel name → w ← n̲umbers kernel n ← t̲ally w k ← n ʰs̲ide 1 n̲ot n = k × k ? "bad-macro-argument left" ⎕R̲EJECT "s:s_tencil< takes a square kernel: 1, 9, 25, ... numbers" c ← (k − 1) d̲iv 2 i ← (r̲ange n) − 1 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 t ← cells ʰt̲erms name 0 = t̲ally t ? "(0 * " c̲at name c̲at ")" "(" c̲at t c̲at ")" }
ʰs̲ide : Int -> Int -> Int
ʰs̲ide ← { n k → n ≤ k × k ? k◆ n ʰs̲ide k + 2 }
Used in: ᵐs̲tencil<, ʰs̲ide
ʰt̲erms : Float -> Char -> Char
ʰt̲erms ← { cells name → 0 = t̲ally cells ? "" rest ← (3 d̲rop cells) ʰt̲erms name w ← f̲irst cells w = 0.0 ? rest t ← (3 t̲ake cells) ʰt̲erm name 0 = t̲ally rest ? t t c̲at " + " c̲at rest }
Used in: ᵐs̲tencil<, ʰt̲erms
ʰt̲erm : Float -> Char -> Char
ʰt̲erm ← { cell name → w ← f̲irst cell b ← (f̲loor 2 s̲elect cell) ʰr̲ows (f̲loor 3 s̲elect cell) ʰc̲ols name w = 1.0 ? b w = -1.0 ? "(n_eg " c̲at b c̲at ")" "(" c̲at (ʰn̲um w) c̲at " * " c̲at b c̲at ")" }
Used in: ʰt̲erms
ʰc̲ols : Int -> Char -> Char
ʰc̲ols ← { d name → d = 0 ? name◆ "(" c̲at (f̲ormat d) c̲at " o_-_2 " c̲at name c̲at ")" }
Used in: ʰt̲erm