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.

source

Stencils

ᵐs̲tencil< : Char -> Char -> Char

macro · line 22

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

function (private) · line 36
ʰs̲ide ← { n k → n ≤ k × k ? k◆ n ʰs̲ide k + 2 }

ʰt̲erms : Float -> Char -> Char

function (private) · line 40
ʰ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
}

ʰt̲erm : Float -> Char -> Char

function (private) · line 54
ʰ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

function (private) · line 63
ʰ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

ʰr̲ows : Int -> Char -> Char

function (private) · line 66
ʰr̲ows ← { d text → d = 0 ? text◆ "(" c̲at (f̲ormat d) c̲at " o_-_1 " c̲at text c̲at ")" }
Used in: ʰt̲erm

ʰn̲um : Float -> Char

function (private) · line 69
ʰn̲um ← { w → w = f̲loat f̲loor w ? f̲ormat f̲loor w◆ f̲ormat w }
Used in: ʰt̲erm