Forthic Idioms
Transforming one thing into another
Often we want a word that transforms something into something else. For instance, we might have a Status and we’d like to convert that into a sort order. We’d use the following naming convention for this: STATUS>ORDER
(note that this is a single Forthic word). The naming convention implies that a status is on the stack before the word is called, and afterwards it will be replaced by a sort order.
Typically, we’d implement this as follows:
: STATUS>ORDER [
["BLOCKED" 1]
["IN PROGRESS" 2]
["DONE" 3]
["TO DO" 4]
] REC SWAP UPPERCASE REC@ 100 DEFAULT;
The first part of the definition is a record:
[
["BLOCKED" 1]
["IN PROGRESS" 2]
["DONE" 3]
["TO DO" 4]
] REC # We'll call this "status_record"
This defines a record that maps keys like DONE
into values like 3
.
The next part of the definition uses SWAP
. Consider the state of the stack right before it’s executed:
Stack: "Done" status_record
After SWAP
is executed, we have this:
Stack: status_record "Done"
The next word is UPPERCASE
, which just makes sure our status is in all caps. After this is executed we have:
Stack: status_record "DONE"
Next, we have the REC@ word. This takes a record and a key and returns it’s associated value:
Stack: 3
The last part of the definition uses DEFAULT
to return a default value of 100 if the key could not be found in the record.
Setting the context for words
In Forthic, we use variable to set the context for other words. For instance, we might use the ticket
variable to set the context for a set of ticket words:
["ticket"] VARIABLES
: ticket-KEY ticket @ 'key' REC@;
: ticket-ASSIGNEE ticket @ 'Assignee' REC@;
: ticket-OOSLA ticket @ 'Due' REC@ DUE>OOSLA;
We use the naming convention varname-WORD
to indicate that a word can assume that the variable has been set. Conversely, once a variable has been set, you can use any of these words at will.
In some situations, multiple variables set a context. In this case we use the following naming convention var1/var2-WORD
. For instance:
: parent/date-COMMENTS parent-COMMENTS-BY-DATE date @ DATE>INT REC@ [] DEFAULT;
: parent/date-COLOR-AS-OF date @ parent-STATUS-AS-OF STATUS>KEY STATUS-KEY>COLOR;