2 ms·
Here is the same for-tree macro processing TXR Lisp's built-in search tree type. That does not use structs, but built in node and tree types. The left, right a
by kazinator 2y ago
Here is the same for-tree macro processing TXR Lisp's built-in search tree type. That does not use structs, but built in node and tree types.
The left, right and key fields of a node object are accessed with like-named functions. We must call tree-root on a tree object to get to the encapsulated root node:
1> (for-tree n (tree-root #T(() 1 2 3 4 5 6 7 8)) (left n) (right n)
(prinl (key n)))
1
2
3
4
5
6
7
8
How about a tree of integers. Let's say the root integer is 1, and to go left is to multiply by 2, and to go right is to multiply by 2 and mask in a 1. And let's say the depth caps out at the value 16:
2> (for-tree n 1 (if (< n 8) (* 2 n)) (if (< n 8) (+ 1 (* 2 n)))
(prinl n))
8
4
9
2
10
5
11
1
12
6
13
3
14
7
15
nil
Let's see that in binary:
3> (for-tree n 1 (if (< n 8) (* 2 n)) (if (< n 8) (+ 1 (* 2 n)))
(format t "~b\n" n))
1000
100
1001
10
1010
101
1011
1
1100
110
1101
11
1110
111
1111
nil
Let's right-align digits to see different patterns in it:
2> (for-tree n 1 (if (< n 8) (* 2 n)) (if (< n 8) (+ 1 (* 2 n)))
(format t "~6b\n" n))
1000
100
1001
10
1010
101
1011
1
1100
110
1101
11
1110
111
1111
nil
Nah, left-aligned wins.
- kazinator 2y agoI forgot I can remove the outer parentheses, and also use infix with C-like operators, since I have those modes turned on in the REPL. (Infix is an unreleased feature, coming in TXR 300). 3> for-tree n 1 (if (n < 8) (n << 1)) (if (n < 8) (n << 1 | 1)) (format t "~b\n" n) 1000 100 1001 10 [...]