It's a bit of a shame that Forth has become almost synonymous with indirect threading implemented in assembly. This is true and somewhat interesting of most implementations, but obfuscates the deeper philosophy of Forth. For me, this is about self-reliance and building your own tools that are suited for the specific task at hand.
I don't care for a lot of the standard forth-isms, such as the way branching and recursion are handled. But I make extensive use of the threaded execution model. One quickly notices that anything that can be pipelined naturally fits into this model. Programming in forth style is often similar to programming with unix pipes except you aren't restricted to string input and output and you do not need to fork subprocesses (though you certainly can!).
Learning how to program in forth, which as so many have pointed out is best done by implementing your own, will fundamentally change the way you program in all languages. Chaining method calls in data pipelining is somewhat forth-like.
As far as implementing a forth, the main interpreter can be written in 14 lines of lua (using lua varargs as the parameter stack):
local thread thread = function(first, next, ...)
if first then
if next then
local cont = thread(next, ...)
return function(...)
return cont(first(...))
end
else
return first
end
else
error "require at least one task"
end
end
Here is how to use it:
local push = function(value)
return function(...)
return value, ...
end
end
local print = function(msg, ...)
print(msg)
return ...
end
local hello_world = thread(push "Hello, world!", print)
hello_world()
And for fun, here is dup:
local dup = function(top, ...) return top, top, ... end
The value of these constructs may not be immediately obvious, but I have built a nice compiler in lua on top of it. (I copied the thread definition above directly from my compiler source code).
I don't care for a lot of the standard forth-isms, such as the way branching and recursion are handled. But I make extensive use of the threaded execution model. One quickly notices that anything that can be pipelined naturally fits into this model. Programming in forth style is often similar to programming with unix pipes except you aren't restricted to string input and output and you do not need to fork subprocesses (though you certainly can!).
Learning how to program in forth, which as so many have pointed out is best done by implementing your own, will fundamentally change the way you program in all languages. Chaining method calls in data pipelining is somewhat forth-like.
As far as implementing a forth, the main interpreter can be written in 14 lines of lua (using lua varargs as the parameter stack):
Here is how to use it: And for fun, here is dup: The value of these constructs may not be immediately obvious, but I have built a nice compiler in lua on top of it. (I copied the thread definition above directly from my compiler source code).