|
|
|
|
|
by Jach
387 days ago
|
|
I have yet to use Forth for anything serious, but it's worth pointing at an example for how expressive you can be dealing with hardware. From https://www.forth.com/embedded/#Embedded_Programming_Example the top level control for a washing machine could be: : WASHER ( -- ) WASH SPIN RINSE SPIN ;
I won't repeat all the rest, even though it's short, but let's look at a few other definitions that build up to that: : RINSE ( -- ) FILL-TUB AGITATE DRAIN ;
: DRAIN ( -- ) PUMP ON 3 MINUTES ;
: ON ( mask -- ) PORT C@ OR PORT C! ;
4 CONSTANT PUMP
01 CONSTANT PORT
All very high level and fairly straightforward to understand word-by-word until you get to the bottom, that being the last 3 lines I pasted. (Though in a file this would be written the other way around with WASHER being the final line.) The PORT is a memory mapped hardware address, PORTB on a 68HC12 chip, and various other constants like PUMP are defined as bitmasks to get at individual bits on the port. The ON word takes the current value at the PORT address, ORs it with the stack-passed mask, and sets it back.In C this might look like (again in reverse order): void washer(void) {
wash();
spin();
rinse();
spin();
}
void drain(void) {
on(PUMP);
minutes(3);
}
void on(uint8_t mask) {
PORT |= mask;
}
#define PUMP (1 << 2)
#define PORT (*(volatile uint8_t *)0x0001)
That is, if you program the C in a similar procedural style that closely follows the physical function of the device. It's maybe more common to express similar C code in a state machine style, in which case it'd look a lot different.Is the Forth version actually worth it? To me the C is "good enough", and more explicit or at least clearer as I'm familiar with C. Where Forth could win me over is in its ease of having a truly interactive environment to iteratively develop the software via a REPL, much like Lisp. (But then I'd rather just use Lisp.) My embedded systems hobby work for the last 10+ years has all been really simple, though, so interactivity isn't a big enough advantage to just using C. (When working with hardware, it's somewhat exciting to stick a pin in a breadboard and move it between power and ground to toggle a motor. It'd be even more exciting to do this interactively via REPL commands poking at memory.) |
|
If you really want to understand the genius of Forth and its creator, I suggest reading everything that Chuck Moore put down in writing starting with "Programming a problem-oriented language".
A lot of us today, being bogged down in the sort of tedium-inducing programming that pays the bills, tend to forget that programming languages are (or should be!) primarily about expressing ideas. Forth is still one of the best languages to do that in.