programdemos/ca-lab/ca-lab.xtl
A cellular automata lab. Every rule here is a lookup table: each cell's neighborhood becomes a number, by rotations and arithmetic over the whole array, and the number picks the cell's next state from the table (s_elect). Changing the rule is changing the table. Run it with "xetal run demos/ca-lab/ca-lab.xtl"; it prints Rule 30 and Rule 90 as sixteen-generation boards, Life, Brian's Brain and Wireworld, each drawn with characters. The live page lets you edit the table and the board, one and two dimensions each their own view: https://softwarewrighter.github.io/X_eTaL-demos/ca-lab/
ᵘb̲its : Int -> Int
-- one dimension: Wolfram's elementary rules. u:b_its rule: a rule number's 8 bits are the table: the next state for each of the 8 neighborhoods (left, center, right), numbered 4 * left + 2 * center + right.
ᵘb̲its ← { rule → (rule d̲iv 2 ^ o̲ffsets 8) m̲od 2 }
ᵘr̲ow : a -> Int -> a
u:r_ow tbl r: the next row. Each cell's neighborhood number, by rotation, looks up its next state in the table (1 + because s_elect counts from 1).
ᵘr̲ow ← { tbl r → (1 + (4 × -1 o̲- r) + (2 × r) + 1 o̲- r) s̲elect tbl }
ᵘg̲row : Int -> Int -> Int
u:g_row tbl h: the history grows downward: rotate the rows up one, and put the next row (of the last one) at the bottom. Start with every row the first.
ᵘg̲row ← { tbl h → g ← f̲irst s̲hape h n ← 2 s̲elect s̲hape h keep ← 1 × ((o̲ffsets g) < g − 1) 'l̲eft t̲able o̲ffsets n (keep × 1 o̲-₁ h) + (1 − keep) × (g c̲at n) r̲eshape tbl ᵘr̲ow g s̲elect h }
Two dimensions: a table on (state, neighbors in state 1)
ᵘc̲ount : (Num a, Num b, Truthy b) => a -> b
u:c_ount b: each cell's number of neighbors in state 1 (alive, firing, an electron's head): nine rotated copies of b = 1 summed, minus the cell itself.
ᵘc̲ount ← { b → ('+ r̲/₁₂ -1 0 1 o̲-₁₂ 1 × b = 1) − 1 × b = 1 }
ᵘl̲ook : a -> Int -> a
u:l_ook tbl b: the next state from a table with a row per state and a column per count: each cell's number is its state * 9 plus its count of live neighbors.
ᵘl̲ook ← { tbl b → (1 + (9 × b) + ᵘc̲ount b) s̲elect tbl }
glider : Int
glider ← 6 6 r̲eshape 0 1 0 0 0 0 0 0 1 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
brain : Int
brain ← 0 0 1 0 0 0 0 0 0 2 2 2 2 2 2 2 2 2 0 0 0 0 0 0 0 0 0
b0 : Int
b0 ← 6 6 r̲eshape 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
wire : Int
wire ← 0 0 0 0 0 0 0 0 0 2 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 3 3 1 1 3 3 3 3 3 3
w0 : Int
w0 ← 3 8 r̲eshape 0 0 0 0 0 0 0 0 2 1 3 3 3 3 3 3 0 0 0 0 0 0 0 0