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?
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
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With