← Starting Henceforth
Episode 8
Loops
Teach the dog to repeat — count up, count down, compound, and ask a question every step.
2:42 · Waltz of the Flowers (Nutcracker, Op. 71)
Watch here · code in the app
Henceforth is the real terminal — one purchase ($9.99) for iPhone, iPad and Mac. Type the commands below into the app as you watch.
Code along
Tap to copy, then type it into Henceforth.
What you’ll learn
- ✓ do … loop counts between two numbers, and they go on the stack first: 11 1 do runs i from 1 up to 10 — it stops just before the limit.
- ✓ begin … until loops until a test comes true — the counter lives on the stack the whole way down, with dup to peek and 1 - to step it.
- ✓ An if inside a loop asks a question every step: 101 0 do i prime? if i . then loop prints every prime under a hundred — a loop, a decision, and the stack.
Transcript
- every word so far runs once. what if i want it again — and again?
- a loop. i write the steps once, and say how many.
- first, two numbers land on the stack — eleven, then one.
- do takes them both: start at one, stop just before eleven.
- one, two, three … ten. ten loops.
- and each turn, i drops on the stack — the dot prints it, then clears it off.
- and when i don't know how many times?
- ten goes on the stack — and stays there, counting.
- dup copies it to print; 1 - takes one off the top.
- until checks the top: is it zero yet?
- watch the stack count itself down — ten to one.
- loops do real work. watch money grow.
- twelve percent a year is times 112, over 100 — the */ word.
- 100 sats sit on the stack — the running total.
- the same do loop — one to ten. ten years.
- each year, */ grows the total on the stack. 100 becomes 304 — it triples.
- and a decision, inside a loop?
- prime? is already written — it asks if a number has any divisor.
- this loop runs zero to a hundred.
- each turn, i goes on the stack; prime? takes it, leaves a yes or no.
- if yes — print it.
- every prime under a hundred — a loop, asking a question of the stack.
- why teach the dog to repeat?
- bitcoin script loops too — counting, checking, until a rule is met.
- more in episode ten.
- henceforth.