Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get n-th element from stack in Forth

Tags:

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?

like image 274
sashoalm Avatar asked Dec 06 '22 05:12

sashoalm


2 Answers

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

like image 200
Joachim Isaksson Avatar answered Dec 31 '22 00:12

Joachim Isaksson


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

like image 29
Lars Brinkhoff Avatar answered Dec 31 '22 01:12

Lars Brinkhoff