programdemos/sandpile/sandpile.xtl
The abelian sandpile: drop grains on a grid; a cell with 4 or more grains topples, giving one to each of its four neighbors, and grains that fall off the edge are lost. Repeat until every cell has fewer than 4. The order of the topples does not matter (that is what abelian means), so every cell topples at once, as often as it can: one array expression a round. The stable pile is a fractal. Run it with "xetal run demos/sandpile/sandpile.xtl"; it prints whether the pile is stable, the grains left, the total topples, and the pile drawn with characters. The live page runs it round by round, colored by grains, and lets you drop more: https://softwarewrighter.github.io/X_eTaL-demos/sandpile/
side : Int
side, grains, rounds: the grid's side (the outer ring is the edge, where grains fall off), grains dropped at the center, rounds to run.
side ← 21
row : Int
-- the edge: a ring of cells that loses what it gets. row, col: each cell's position, by broadcasting. edge, inside: each cell's distance to the border, and whether it is inside (the ring has 0).
row ← (o̲ffsets side) 'l̲eft t̲able o̲ffsets side
One round: every cell topples as often as it can
ᵘt̲opple : Int -> Int
u:t_opple h: q is how many times each cell topples: its grains over 4. It keeps h - 4 q and gets q from each of its four neighbors (four rotations, g); the edge is outside, so its grains fall off.
ᵘt̲opple ← { h → q ← h d̲iv 4 g ← (1 o̲-₁ q) + (-1 o̲-₁ q) + (1 o̲-₂ q) + -1 o̲-₂ q inside × (h − 4 × q) + g }
ᵘs̲table : (Num a, Num b, Truthy b) => a -> b
u:s_table h: whether no cell has 4 or more.
ᵘs̲table ← { h → 1 × 4 > 'm̲ax r̲/₁₂ h }
A round that also counts the topples
ᵘp̲lane : a -> a
u:p_lane m: a matrix as one plane of a rank-3 array, for stacking with c_at. u:s_tep s: the state s is two planes, the grains and how many times each cell has toppled so far (the avalanche's shape).
ᵘp̲lane ← { m → (1 c̲at s̲hape m) r̲eshape m }
ᵘs̲tep : Int -> Int
ᵘs̲tep ← { s → h ← 1 s̲elect s (ᵘp̲lane ᵘt̲opple h) c̲at ᵘp̲lane (2 s̲elect s) + h d̲iv 4 }