In Forth, is there a common word to conditionally exit a procedure (return) if the top of the stack is zero? I was thinking of using this in recursive procedures instead of IF.
There is a commonly implemented word called "?exit" which will exit if not zero. You will have to do:
0= ?exit
To get what you want. If your Forth lacks this, you can define it yourself, but it requires knowledge of the implementation details of the Forth to implement correctly strictly speaking. On most Forths however, the following code will work:
: ?exit if rdrop exit then ;
: ?exit if r> drop exit then ; ( if "rdrop" is not available )
: -?exit 0= if rdrop exit then ; ( what you want )
Most Forth implementations just have a single value used for each function call, so this will work on the majority of them.
And a more portable version:
: ?exit postpone if postpone exit postpone then ; immediate
: -?exit postpone 0= postpone if postpone exit postpone then ; immediate
Although I have noticed not all Forth implementations have implemented "postpone", and may instead use a word like "[compile]".
A portable implementation:
: ?exit ( x -- ) postpone if postpone exit postpone then ; immediate
: 0?exit ( x -- ) postpone 0= postpone ?exit ; immediate
This implementation works on any standard Forth system.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With