5

Rosetta Codeでは、Forth に Y-combinator の実装はありません。

どうやってやるの?Forth で Y-combinator を使用するにはどうすればよいですか? なぜ?

4

2 に答える 2

5

Yコンビネータでの私の試みは次のとおりです。xt に適用yすると、別の xt が返されます。この新しい xt を実行すると、最初の xt が実行され、2 番目の 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

于 2016-02-05T08:48:03.147 に答える