Search code examples
stackesoteric-languagesbefunge

How to pop Nth item in the stack [Befunge-93]


If you have the befunge program 321&,how would you access the first item (3) without throwing out the second two items?

The instruction \ allows one to switch the first two items, but that doesn't get me any closer to the last one...

The current method I'm using is to use the p command to write the entire stack to the program memory in order to get to the last item. For example,

32110p20p.20g10g@

However, I feel that this isn't as elegant as it could be... There's no technique to pop the first item on the stack as N, pop the Nth item from the stack and push it to the top?

(No is a perfectly acceptable answer)


Solution

  • Not really. Your code could be shortened to

    32110p\.10g@
    

    But if you wanted a more general result, something like the following might work. Below, I am using Befunge as it was meant to be used (at least in my opinion): as a functional programming language with each function getting its own set of rows and columns. Pointers are created using directionals and storing 1's and 0's determine where the function was called. One thing I would point out though is that the stack is not meant for storage in nearly any language. Just write the stack to storage. Note that 987 overflows off a stack of length 10.

    v           >>>>>>>>>>>12p:10p11pv
                1    0   v<<<<<<<<<<<<<<<<<<
                         v   >210gp10g1-10p^
                         >10g|
                             >14p010pv
                         v<<<<<<<<<<<<<<<<<<<<<<<<
                         v       >210g1+g10g1+10p^
                         >10g11g-|
                   v       g21g41<
                 v _ v
    >98765432102^>.  2^>.@
    

    The above code writes up to and including the n-1th item on the stack to 'memory', writes the nth item somewhere else, reads the 'memory', then pushes the nth item onto the stack. The function is called twice by the bottom line of this program.