I'm a recovering programmer who has been designing video games since the 1980s, doing things that seem baroquely hardcore in retrospect, like writing Super Nintendo games entirely in assembly language. These days I use whatever tools are the most fun and give me the biggest advantage.
james.hague @ gmail.com
Where are the comments?
Understanding What It's Like to Program in ForthI write Forth code every day. It is a joy to write a few simple words and solve a problem. As brain exercise it far surpasses cards, crosswords or Sudoku
I've used and enjoyed Forth quite a bit over the years, though I rarely find myself programming in it these days. Among other projects, I've written several standalone tools in Forth, used it for exploratory programming, wrote a Forth-like language for handling data assets for a commercial project, and wrote two standalone 6502 cross assemblers using the same principles as Forth assemblers.
It's easy to show how beautiful Forth can be. The classic example is:
Chuck Moore's Sudoku quote above is one of the most accurate characterizations of Forth that I've seen. Once you truly understand it, you'll better see what's fun about the language, and also why it isn't as commonly used. What I'd like to do is to start with a trivially simple problem, one that's completely straightforward, even simpler than the infamous FizzBuzz:
Write a Forth word to add together two integer vectors (a.k.a. arrays) of three elements each.The C version, without bothering to invent custom data types, requires no thought:
First Forth AttemptSo now, Forth. We start with a name and stack picture:
rot" brings v1 to the top, then we grab the first element of the array (remember that we need to keep v1 around, hence the
dup). Hmmm...now we've got four items on the stack:
pick, so we're stuck.
Second Forth AttemptThinking about this a bit more, the problem is we have too many items being dealt with at once, too many items on the stack. v3 sitting there on top is getting in the way, so what if we moved it somewhere else for a while? The return stack is the standard location for a temporary value, so let's try it:
Third Forth AttemptThis isn't as bad as it sounds. We can just keep v3 over on the return stack for the whole function. Here's an attempt at the full version of
cell+is roughly the same as
++in C. "
2 cells +" is equivalent to "
cell+ cell+". Notice how v3 stays on the return stack for most of the function, being fetched with
r@. The "
drop drop" at the end is to get rid of v1 and v2. Some nicer formatting helps show the symmetry of this word:
Still, it was enjoyable to work this out. Better than Sudoku? Yes.