sourcelibs/Graphs/src/Graphs.xtlm
1⍝# Graphs: its macro library -- g_raph<, a graph written by its names.
2⍝# Imported with the functions, under one alias: "g:" u_se< "Graphs".
3⍝# A macro is a function from the source text written left and right of
4⍝# its call to the source that replaces the call, run before the program
5⍝# is compiled (X_eTaL MC10). Names with m: are macros; those under h: are
6⍝# private to this file.
7
8ᵗ⁼u̲se< "Strings"
9
10lowers ← "abcdefghijklmnopqrstuvwxyz"
11letters ← lowers c̲at ⎕A c̲at ⎕D
12
13⍝## Parsing
14
15⍝# The lists of a list joined into one list.
16ʰr̲aze ← { b → d̲isclose '{ e̲nclose (d̲isclose ⍺) c̲at d̲isclose ⍵ } r̲/ b }
17
18⍝# Whether a text can be a variable's name: a lowercase letter, then
19⍝# letters and digits.
20ʰn̲ame? ← { n → (0 < t̲ally n) ∧ ((f̲irst n) m̲ember? lowers) ∧ '∧ r̲/ n m̲ember? letters }
21
22⍝# The paths of a graph text: a list per path, its stations in order.
23ʰp̲aths ← { t → '{ p → '{ s → ᵗt̲rim d̲isclose s } m̲ap "-" ᵗs̲plit ᵗt̲rim d̲isclose p } m̲ap "," ᵗs̲plit t }
24
25⍝## The macro
26
27⍝# "town" g:g_raph< "airport-bridge-center, center-docks": the graph
28⍝# written by its names, paths of stations joined by "-", paths
29⍝# separated by ",". When the program is compiled it defines a variable
30⍝# per station, numbered in order of first appearance (airport := 1,
31⍝# bridge := 2, ...), and town as the adjacency matrix, every edge both
32⍝# ways, so the rest of the program speaks of stations by name
33⍝# (town g:l_evels center). It stands as a statement of its own. A name
34⍝# that cannot be a variable stops the compiler at it: error[bad-name].
35ᵐg̲raph< ← { name t →
36 ps ← ʰp̲aths t
37 stations ← u̲nique ʰr̲aze ps
38 n̲ot ʰn̲ame? name ? "bad-name left" ⎕R̲EJECT name c̲at " cannot be a variable's name: a lowercase letter, then letters and digits"
39 bad ← (n̲ot '{ ʰn̲ame? d̲isclose ⍵ } e̲ach stations) r̲eplicate stations
40 0 < t̲ally bad ? "bad-name right" ⎕R̲EJECT (d̲isclose f̲irst bad) c̲at " cannot be a station's name: a lowercase letter, then letters and digits"
41 n ← t̲ally stations
42 ⍝ each station's number, path by path; neighbors on a path are edges
43 ks ← '{ p → stations i̲ndexOf d̲isclose p } m̲ap ps
44 a ← ʰr̲aze '{ k → -1 d̲rop d̲isclose k } m̲ap ks
45 b ← ʰr̲aze '{ k → 1 d̲rop d̲isclose k } m̲ap ks
46 from ← a c̲at b ⍝ both ways
47 to ← b c̲at a
48 at ← (n × from − 1) + to
49 m ← (r̲ange n × n) m̲ember? at
50 defs ← "\n" ᵗj̲oin '{ i → (d̲isclose i s̲elect stations) c̲at " := " c̲at f̲ormat i } m̲ap r̲ange n
51 defs c̲at "\n" c̲at name c̲at " := " c̲at (f̲ormat n) c̲at " " c̲at (f̲ormat n) c̲at " r_eshape " c̲at f̲ormat 0 + m
52}