在Forth中有条件退出这个词吗?



在Forth中,如果堆栈顶部为零,是否有一个通用词来有条件地退出一个过程(返回)?我正在考虑在递归过程中使用这个而不是IF。

有一个常用的实现词叫做"?exit"如果不是为零,则退出。你必须这样做:

0= ?exit

得到你想要的。如果您的Forth缺少这个,您可以自己定义它,但是严格地说,它需要了解Forth的实现细节才能正确地实现。然而,在大多数forth上,下面的代码可以工作:

: ?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 )

大多数Forth实现对于每个函数调用只有一个单独的值,所以这将在大多数情况下工作。

和一个更便携的版本:

: ?exit postpone if postpone exit postpone then ; immediate
: -?exit postpone 0= postpone if postpone exit postpone then ; immediate

虽然我注意到并非所有的Forth实现都实现了&;postpone&;,而可能会使用&;[compile]&;之类的词。

一个可移植的实现:

: ?exit ( x -- ) postpone if postpone exit postpone then ; immediate
: 0?exit ( x -- ) postpone 0= postpone ?exit ; immediate

此实现适用于任何标准的Forth系统。

最新更新