sourcelibs/Csv/src/Csv.xtlm
1⍝│ Csv: its macro library -- c_olumns<, a table's columns as named,
2⍝│ typed variables.
3⍝│ Imported with the functions, under one alias: "cs:" u_se< "Csv".
4⍝│ A macro is a function from the source text written left and right of
5⍝│ its call to the source that replaces the call, run before the program
6⍝│ is compiled (X_eTaL MC10). Names with m: are macros; those under h: are
7⍝│ private to this file.
8
9"t:" u̲se< "Strings"
10"pa:" u̲se< "Parsing"
11
12⍝━━ Parsing
13
14⍝│ A column's name and kind, from "name:kind": the colon's position
15⍝│ (Parsing's pa:a_t) cuts it.
16ʰc̲olon ← { c → ":" ᵖᵃa̲t c }
17ʰc̲olName ← { c → ((ʰc̲olon c) − 1) t̲ake c }
18ʰc̲olKind ← { c → (ʰc̲olon c) d̲rop c }
19
20⍝│ Whether a column is "name:text" or "name:number": a lowercase
21⍝│ name (Parsing's pa:n_ame?); name and kind split the column
22⍝│ completely, so nothing between them is ever dropped.
23ʰc̲olumn? ← { c →
24 1 ≠ t̲ally w̲here c = f̲irst ":" ? 0 = 1
25 (ᵖᵃn̲ame? ʰc̲olName c) ∧ ("text" m̲atch ʰc̲olKind c) ∨ "number" m̲atch ʰc̲olKind c
26}
27
28⍝│ The code for one column of table tb: its texts, found by header, the
29⍝│ header left out; numbers read from them when the kind is number.
30ʰc̲ode ← { tb c →
31 n ← ʰc̲olName c
32 texts ← "(1 d_rop ((f_irst " c̲at tb c̲at ") i_ndexOf e_nclose \"" c̲at n c̲at "\") s_elect_2 " c̲at tb c̲at ")"
33 "text" m̲atch ʰc̲olKind c ? n c̲at " := " c̲at texts
34 n c̲at " := n_umbers d_isclose '{ e_nclose (d_isclose _l) c_at \" \" c_at d_isclose _r } r_/ " c̲at texts
35}
36
37⍝━━ The macro
38
39⍝│ "city:text population:number" cs:c_olumns< "t": the columns of table
40⍝│ t (a table as cs:r_ows gives it, its first row the header) as
41⍝│ variables named after them: city the texts of column "city",
42⍝│ population its numbers (Floats). When the program is compiled the
43⍝│ schema is checked and a definition written per column, so the rest
44⍝│ of the program uses the columns by name and their kinds are
45⍝│ type-checked like any variable (population c_at "x" is a type
46⍝│ error). A malformed schema or table name stops the compiler:
47⍝│ error[bad-columns]. Columns are found by their header when the
48⍝│ program runs.
49⍝│ takes: text code
50⍝│ uses: parsed
51ᵐc̲olumns< ← { schema tb →
52 cs ← ᵗw̲ords schema
53 0 = t̲ally cs ? "bad-columns left" ⎕R̲EJECT "no columns: write name:text or name:number"
54 bad ← (n̲ot '{ ʰc̲olumn? d̲isclose ⍵ } e̲ach cs) r̲eplicate cs
55 0 < t̲ally bad ? "bad-columns left" ⎕R̲EJECT (d̲isclose f̲irst bad) c̲at " is not a column: write name:text or name:number (a lowercase name)"
56 n̲ot ᵖᵃn̲ame? ᵗt̲rim tb ? "bad-columns right" ⎕R̲EJECT tb c̲at " is not a table's name"
57 "\n" ᵗj̲oin '{ c → (ᵗt̲rim tb) ʰc̲ode d̲isclose c } m̲ap cs
58}