sourcedemos/combinators.xtl
1⍝!/usr/bin/env xetal
2⍝# Combinators: the Combinators library, Smullyan's birds, each a
3⍝# function that only rearranges, repeats or drops its arguments. Run it
4⍝# with "xetal run demos/combinators.xtl" (or "./demos/combinators.xtl"),
5⍝# or as a notebook with "just show demos/combinators.xtl"; it prints
6⍝# what each bird makes of small numbers, ending with 10 factorial from
7⍝# Y and 1024 from a function power. docs/birds.md lists every bird.
8
9⍝## The library and two helpers
10
11ᶜ⁼u̲se< "Combinators"
12
13⍝ A quoted function before a bird is its first argument; a value on
14⍝ the left comes next, then the one on the right.
15
16⍝# u:i_nc x: x plus one.
17ᵘi̲nc ← { ⍵ + 1 }
18
19⍝# u:d_ouble x: x times two.
20ᵘd̲ouble ← { ⍵ × 2 }
21
22⍝## The birds
23
24⍝ K keeps its first argument and drops the second.
251 ᶜK̲ 2
26
27⍝ C, the Cardinal, swaps the arguments of a function: 10 - 3 becomes
28⍝ 3 - 10.
2910 '− ᶜC̲ 3
30
31⍝ B, the Bluebird, composes: double first, then add one.
32'ᵘd̲ouble 'ᵘi̲nc ᶜB̲ 5
33
34⍝ W, the Warbler, duplicates an argument: 4 * 4.
35'× ᶜW̲ 4
36
37⍝ S, the Starling: x z (y z), here 3 + (3 * 2).
38'ᵘd̲ouble '+ ᶜS̲ 3
39
40⍝ T, the Thrush, applies its second argument to its first.
413 ᶜT̲ 'ᵘd̲ouble
42
43⍝ V, the Vireo, holds a pair until a function arrives.
44(3 ᶜV̲ 4)_ '+
45(3 ᶜV̲ 4)_ '×
46
47⍝## Recursion from Y, and function power
48
49⍝# 's_elf u:f_act n: the factorial of n, recursing through s_elf, the
50⍝# function it is handed (lazy, ~), rather than by its own name. Y, the
51⍝# Sage Bird, hands it itself: 'ᵘf̲act ᶜY̲ 10 is 10 factorial.
52ᵘf̲act ← { ~s̲elf n → n ≤ 1 ? 1◆ n × s̲elf n − 1 }
53'ᵘf̲act ᶜY̲ 10
54
55⍝ Function power: a superscript repeats a function.
56ᵘd̲ouble¹⁰ 1