sourcedemos/macros.xtl
1⍝!/usr/bin/env xetal
2⍝# Macros write source for you: a call "left" n_ame< "right" is replaced,
3⍝# before the program is checked, by the source the macro writes from the
4⍝# two texts. Run it with ./demos/macros.xtl (or xetal run): it prints what
5⍝# the system macros give, then a macro library's checks; a failed a_ssert<
6⍝# goes to standard error. Read each call beside its expansion, which
7⍝# "xetal expand demos/macros.xtl" shows.
8
9⍝## System macros
10⍝ i_f< chooses between two expressions when the program runs; only the
11⍝ one chosen is evaluated.
12⍝# The number the conditions below test: negative, so x > 0 is false.
13x ← -3
14"x > 0" i̲f< "1; -1"
1510 × "x > 0" i̲f< "1; -1"
16"x < 0" i̲f< "0; 1 / 0"
17⍝ u_nless< runs statements unless a condition holds; its value is @.
18"x = 0" u̲nless< "p_rint! 100 / x"
19
20⍝# u:m_ax/ v, u:m_in/ v: the largest and smallest item of v, written by
21⍝# e_ach<, one statement per word with $w replaced by the word.
22"m_ax m_in" e̲ach< "u:$w/ := { '$w r_/ _r }"
23ᵘm̲ax/ 3 1 4 1 5
24ᵘm̲in/ 3 1 4 1 5
25⍝ f_ormat< puts values into text, a_ssert< reports a failed condition on
26⍝ standard error and goes on, c_fg< says where it runs (1 cli, 0 live demo).
27@ f̲ormat< "x is {x}, and its square is {x * x}"
28"x > 0" a̲ssert< "x is positive"
29@ c̲fg< "cli"
30
31⍝## Macros of your own
32
33⍝ Macros of your own live in macro libraries (.xtlm files): each is a
34⍝ function from the two texts to the source that replaces the call.
35⍝ Macros (lib/Macros.xtlm) is a small example, imported like a library.
36ᵐ⁼u̲se< "Macros"
37⍝# u:s_quare x: x times x, defined by the m:d_ef< macro.
38"s_quare" ᵐd̲ef< "_r * _r"
39ᵘs̲quare 7
40"4 = 2 + 2" ᵐc̲heck< "addition"
41"5 = 2 * 2" ᵐc̲heck< "doubling"
a̲ssert< expands to
{ @ → (x > 0) ? @◆ ⎕E̲RR "assertion failed: x > 0 (x is positive) [demos/macros.xtl:28]"◆ @ } @c̲fg< expands to
1