Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a word for a conditional exit in Forth?

Tags:

forth

gforth

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.

like image 463
Anthony Avatar asked Feb 18 '21 18:02

Anthony


2 Answers

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]".

like image 71
howerj Avatar answered Sep 21 '22 21:09

howerj


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.

like image 31
ruvim Avatar answered Sep 20 '22 21:09

ruvim