Get n-th element from stack in Forth

899 views Asked by At

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?

2

There are 2 answers

4
Joachim Isaksson On BEST ANSWER
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

1
Lars Brinkhoff On

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.)