2 ms·
Forth has "compile time words". These are sort of like macros in that they are evaluated/expanded at parse/compile time. From what I understand[1], they are gen
by munificent 11y ago
Forth has "compile time words". These are sort of like macros in that they are evaluated/expanded at parse/compile time. From what I understand[1], they are generally replaced with special branch instructions that move the instruction pointer.
So this line of Forth:
3 4 < IF ." OK" ELSE ." WAT" THEN
Means: Evaluate "3 < 4". If it's true, print "OK", otherwise print "WAT". The "IF" "ELSE" and "THEN" words are compile time words. When that line of code is entered, before it's run, they get expanded to something like:
3 4 < ?BRANCH 5 LIT "OK" OUTPUT BRANCH 3 LIT "WAT" OUTPUT
Here, "?BRANCH" is a conditional jump followed by an offset and "BRANCH" is an unconditional jump. Those are built-in and will move the instruction pointer directly, so you get the conditional evaluation you need.
Other stack based languages do this differently. In Factor, it would be:
3 4 < [ "OK" print ] [ "WAT" print ] if
Here, "[" and "]" are "parse words" that at parse time wrap of their contained words and create a quotation out of them. Basically like a closure or thunk—a chunk of code to be executed later if desired. So this code evaluates the condition and puts it on the stack. Then it pushes two quotations onto the stack. Then the "if"[2] word executes. It's just a regular word now. It looks at the condition and, if true, executes the first quotation. Otherwise it runs the second.
In this sense, Factor works like Smalltalk where control flow doesn't need to be special because the language has very terse syntax for explicitly creating a deferred chunk of code[3].
[1]: https://en.wikipedia.org/wiki/Forth_(programming_language) https://en.wikipedia.org/wiki/Forth_(programming_language)
[2]: http://docs.factorcode.org/content/word-if%2Ckernel.html http://docs.factorcode.org/content/word-if%2Ckernel.html
[3]: https://www.gnu.org/software/smalltalk/manual/html_node/Conditions.html https://www.gnu.org/software/smalltalk/manual/html_node/Cond...