

\ This keeps track of how many case? instances we need to clean up after:

0 var, case#



\ This is the runtime effect of case?

: (case?) over n:= dup if nip then ;



\ This is the word you invoke, note that it is 'immediate' so it will take some action at invocation time, and lay down a separate action for run-time

: case? \ x y -- true | x x -- x false

1 case# n:+!

' (case?) p: compile i;



\ Clean up after a series of case? words:

: thens

( p: then )

0 case# xchg times i;





: x

20 case? if 100 else

200 case? if 1000 else

\ default case!

n:1+

thens

. cr ;



1 x

20 x

30 x

200 x

bye





2

100

31

1000





: /* "*/" parse drop i;





/* "hi there" . cr */



"goodbye" . cr

bye



If you're used to most standard programming languages, like C++, Java, or Python, you know you have a fixed syntax which you must adhere to. There is no way to modify the syntax, because it's baked-in to the language.Forths, including 8th, have a much more laissez-faire attitude: there's no syntax to speak of, and you can modify the syntax to suit your needs.In fact, in Forths you are supposed to create your own "domain-specific language" to express the problem you are trying to solve in a manner more in line with your needs.So for example, 8th does not include a standard "case" statement. It hasand, but they act on maps or arrays, and so are perhaps a bit difficult to grasp if you're coming from one of the aforementioned languages. Or they may just be inconvenient for your use-case.Don't worry! You can make your own version of a 'case' construct, if you like - and it's not even difficult:This sample shows how you can, in just a few lines of code, create an entirely new 'conditional statement'. Try that in C++! Don't like the word? Change it to "endcase" or whatever else you prefer.Here's how you use it:This will print:Another example, using "parsing words". You want to make a comment wordbecause that's what you're used to? No problem:Congratulations! You've just created a new comment syntax which didn't exist before! Using it:Only prints "goodbye", as expected. By making theword "immediate", you can also use it inside a word definition and get the result you expect, e.g. comment out bits of code.The point is: 8th (and Forths in general) is very flexible. Don't be fooled by the RPN syntax into thinking that you must always and only do things in one way.