sourcelibs/Tags/demos/turtle.xtl
1⍝!/usr/bin/env xetal
2⍝│ A turtle on a grid: its heading is one of four choices, its state a
3⍝│ tagged tuple of a position, a heading and a count of steps -- parts of
4⍝│ different types, used by name. e_num< names the choices, p_arts< the
5⍝│ parts; both write plain definitions when the program is compiled.
6⍝│ Turns and moves are tables indexed by the heading, not branches.
7⍝│ Run with "just demo Tags turtle".
8
9"tg:" u̲se< "Tags"
10@ ᵗᵍe̲num< "Heading: north east south west"
11@ ᵗᵍp̲arts< "Turtle: at heading steps"
12RIGHT ← EAST c̲at SOUTH c̲at WEST c̲at NORTH ⍝ the heading after a right turn, by heading
13LEFT ← WEST c̲at NORTH c̲at EAST c̲at SOUTH
14MOVE ← 4 2 r̲eshape 0 1 1 0 0 -1 -1 0 ⍝ a step's x and y, by heading
15⍝│ u:f_orward s: one step the way the turtle faces, counted.
16ᵘf̲orward ← { s →
17 next ← (ᵘt̲urtleAt s) + (ᵘt̲urtleHeading s) s̲elect MOVE
18 next ᵘs̲etTurtleAt (1 + ᵘt̲urtleSteps s) ᵘs̲etTurtleSteps s
19}
20⍝│ u:r_ight s and u:l_eft s: a quarter turn, by table.
21ᵘr̲ight ← { s → ((ᵘt̲urtleHeading s) s̲elect RIGHT) ᵘs̲etTurtleHeading s }
22ᵘl̲eft ← { s → ((ᵘt̲urtleHeading s) s̲elect LEFT) ᵘs̲etTurtleHeading s }
23start ← ᵘt̲urtle (0 0, NORTH, 0)
24start
25up ← 3 'ᵘf̲orward p̲ower start ⍝ three steps north
26over ← 2 'ᵘf̲orward p̲ower ᵘr̲ight up ⍝ right, two steps east
27back ← ᵘf̲orward ᵘl̲eft ᵘl̲eft over ⍝ about turn, one step west
28back
29"now at " c̲at (f̲ormat ᵘt̲urtleAt back) c̲at ", facing " c̲at (d̲isclose (ᵘt̲urtleHeading back) s̲elect HEADING) c̲at ", after " c̲at (f̲ormat ᵘt̲urtleSteps back) c̲at " steps"
ᵗᵍe̲num< expands to
NORTH ← 1 EAST ← 2 SOUTH ← 3 WEST ← 4 HEADING ← "north" "east" "south" "west"
ᵗᵍp̲arts< expands to
TURTLE ← "Turtle" ᵘt̲urtle ← { (at, heading, steps) → (TURTLE, at, heading, steps) } ᵘt̲urtle? ← { (g1:tag, _, _, _) → g1:tag m̲atch TURTLE } ᵘt̲urtleAt ← { (g1:tag, g2:part, _, _) → n̲ot g1:tag m̲atch TURTLE ? "wrong-kind" ⎕S̲IGNAL "expected a Turtle" g2:part } ᵘt̲urtleHeading ← { (g1:tag, _, g2:part, _) → n̲ot g1:tag m̲atch TURTLE ? "wrong-kind" ⎕S̲IGNAL "expected a Turtle" g2:part } ᵘt̲urtleSteps ← { (g1:tag, _, _, g2:part) → n̲ot g1:tag m̲atch TURTLE ? "wrong-kind" ⎕S̲IGNAL "expected a Turtle" g2:part } ᵘs̲etTurtleAt ← { g3:new (g1:tag, at, heading, steps) → n̲ot g1:tag m̲atch TURTLE ? "wrong-kind" ⎕S̲IGNAL "expected a Turtle" _ ← g3:new m̲atch at (g1:tag, g3:new, heading, steps) } ᵘs̲etTurtleHeading ← { g3:new (g1:tag, at, heading, steps) → n̲ot g1:tag m̲atch TURTLE ? "wrong-kind" ⎕S̲IGNAL "expected a Turtle" _ ← g3:new m̲atch heading (g1:tag, at, g3:new, steps) } ᵘs̲etTurtleSteps ← { g3:new (g1:tag, at, heading, steps) → n̲ot g1:tag m̲atch TURTLE ? "wrong-kind" ⎕S̲IGNAL "expected a Turtle" _ ← g3:new m̲atch steps (g1:tag, at, heading, g3:new) } ᵘt̲urtleRows ← { g4:which (g1:tag, at, heading, steps) → (g1:tag, g4:which s̲elect at, g4:which s̲elect heading, g4:which s̲elect steps) }