Reading Loops from the Inside Out
Nalbinding asks you to read your own work as you go. A new loop passes through earlier ones, and a stitch that looks plausible from the front can tell a different story when you trace the yarn. Joining in a fresh length only adds another reason to pay attention to where the strand goes.
For today’s notebook, imagine a much simpler notation: ( opens a loop and ) closes it. This is not a complete notation for nalbinding stitches; it is a small model for one question: are the loops properly nested?
fun main() {
val stitches = "(()())"
var depth = 0
var valid = true
for (stitch in stitches) {
depth += if (stitch == '(') 1 else -1
if (depth < 0) valid = false
}
println(if (valid && depth == 0) "balanced" else "unbalanced")
}
The Kotlin version tracks how many loops are still open. A closing loop takes one away; if the count ever falls below zero, a loop was closed before it opened. Ending at zero matters too: otherwise, some loops remain open. Both checks are needed, as )( has equal numbers of each mark but fails immediately.
Forth can make the same pass over a string. Its depth and valid variables hold the two pieces of information between characters:
variable depth
variable valid
: check-loops ( addr len -- )
0 depth ! true valid !
bounds ?do
i c@ 40 = if 1 else -1 then depth +!
depth @ 0< if false valid ! then
loop
valid @ depth @ 0= and if
." balanced" else ." unbalanced" then cr ;
s" (()())" check-loops
bye
Both programs print balanced. They assume the input contains only parentheses; a real stitch reader would also need to reject other characters and represent crossings, direction and the route through earlier loops. The reward for this narrow model is that the check needs just one pass and a counter, however long the strand of symbols becomes.