Rosetta Code上,Forth中没有实现Y组合器。

我怎样才能做到这一点?如何在Forth中使用Y组合器?又为什么呢?

最佳答案

这是我尝试使用Y组合器的尝试。当您将y应用于xt时,您会得到另一个xt。当您执行此新xt时,它将执行第一个xt并传入第二个xt。

\ Address of an xt.
variable 'xt
\ Make room for an xt.
: xt, ( -- ) here 'xt !  1 cells allot ;
\ Store xt.
: !xt ( xt -- ) 'xt @ ! ;
\ Compile fetching the xt.
: @xt, ( -- ) 'xt @ postpone literal postpone @ ;
\ Compile the Y combinator.
: y, ( xt1 -- xt2 ) >r :noname @xt, r> compile, postpone ; ;
\ Make a new instance of the Y combinator.
: y ( xt1 -- xt2 ) xt, y, dup !xt ;

使用例如像这样:
\ Count down from 10; passed to the anonymous definition.
10
\ Anonymous definition which recursively counts down.
:noname ( u xt -- ) swap dup . 1- ?dup if swap execute else drop then ;
\ Apply the Y combinator and execute the result.
y execute
\ Should print 10 9 8 7 6 5 4 3 2 1.

至于为什么,没有实际的原因。这是函数递归调用自身而不用显式命名函数的一种方式。但是(标准)Forth甚至在RECURSE定义中也具有:NONAME

关于computer-science - 如何在Forth中实现Y组合器?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35199836/

10-09 18:40