'Get n-th element from stack in Forth

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

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



Solution 1:[1]

500 PICK

...will copy the element 500 levels down the stack to the top of the stack in Forth79.

More relevant: PICK is in the core extension wordset in ISO93 Forth, the base of the current standard. The definition of PICK in this standard is 0-based, e.g. '0 PICK' is equivalent to 'DUP'. See section 6.2.2030

Solution 2:[2]

And if the Forth you're using don't have PICK, you could define it as

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

(Of course, an iterative version would also be possible.)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Albert van der Horst
Solution 2 Lars Brinkhoff