Get the nth item from the stack in Fort

Is there a way to access a stack element by its index in Forth without selecting all the elements above it?

For example, if I have numbers from 1 to 1000 pushed onto the stack, how can I get the 500th element?

+4
source share
2 answers
500 PICK 

... will copy the 500 level item down the stack to the top of the stack in Forth79.

+8
source

And if you use PICK at Fort, you can define it as

 : PICK ?DUP IF SWAP >R 1- RECURSE R> SWAP EXIT THEN DUP ; 

(Of course, an iterative version is also possible.)

+5
source

Source: https://habr.com/ru/post/1500596/


All Articles