
On this seventh day of Nockmas, we investigate opcode 6, Conditional. The first of our composite opcodes. The composite opcodes combine multiple operations into higher-level constructs. While not strictly necessary for a complete instruction set, they offer the necessary affordances for practical programming in Nock.
Opcode 6: Conditional
Syntax
*[a 6 b c d] *[a *[[c d] 0 *[[2 3] 0 *[a 4 4 b]]]]
Explanation
Opcode 6 implements a conditional branch. Evaluate test formula b; if true (0), evaluate and return c; if false (1), evaluate and return d. Crashes on non-boolean test results.
- Evaluate
bagainst the subject, which must produce 0 or 1. - If 0 (true): evaluate
cagainst subject and return. - If 1 (false): evaluate
dagainst subject and return.
Any other value crashes (as enforced by the macro expansion).
In fact, much of the weirdness of the macro expression can be explained by its parsimonious use of the boolean result. From right to left:
*[a 4 4 b]evaluates b, then adds 2 (so 0 → 2, 1 → 3).*[[2 3] 0 ...]uses the result as an address into[2 3].*[[c d] 0 ...]uses 2 or 3 as address into[c d].
This cleverly selects c (at address 2) for true, d (at address 3) for false. (It does not pass through directly to avoid other results selecting other possible slots.)
You'll be familiar now with our favorite subject:
:subject 42
Output:
Subject set to: 42
You need an expression that results in 0 or 1 to use as the test. For example, to test whether the subject is equal to a value such as 42, use opcode 5:
[6 [5 [1 42] [0 1]] [1 100] [1 0]]
Output:
100
This is how to implement a NOT operator on a loobean value:
:subject 0
Output:
Subject set to: 0
[6 [5 [1 0] [0 1]] [1 1] [1 0]]
Output:
1
For more on opcode 6 as a composite opcode used to build "if-then-else", check out the Urbit docs.
Join us tomorrow when we cover Nock 7, Compose.
12 Days of Nockmas is an exploration of Nock, Urbit's instruction set architecture. This ISA is used by both Urbit and Nockchain, has interpreters written in many languages, with production versions in both C and Rust. The content of this series is drawn from the Nock language site. Visit the site for interactive code examples and more Nock related content.