dc: how do I pop (and discard) the top number of the stack?
Asked Answered
Q

1

7

In dc, how do I pop and discard a number from the top of the stack? A stack with three items (1 2 3) should become a stack with two items (2 3). Currently I'm shoving the number onto another stack (Sz) but that seems rather lame.

Qp answered 21/6, 2013 at 23:21 Comment(2)
How can it be that something is on the stack, that you dont want?Midinette
@hendrik: If you have a counter which you use to control the number of iterations of a loop, then when the loop finishes you have to discard the counter.Xantha
P
8

There are numerous ways to delete the top of the stack but they have side effects. Removing an element without side effects requires you to avoid included side effects.

To remove the top of the stack without a side effect, ensure that the top is a number and then run d!=z. If the stack had [5], this does the following

  1. Start with item to remove. Stack: [5]
  2. Duplicate top of stack. Stack: [5,5]
  3. Pop top 2 and test if they are not equal: 5 != 5 Stack: []
  4. If test passed (which it can't), run z Stack: []

To ensure that the top of stack is a number, I use Z which will calculate the length of a string or the number of digits in a number and push that back. There are other options such as X. Anything that makes a number out of anything will work so that it will be compatible with !=.

So the full answer for copy pasting in all situations is the following:

Zd!=r

I usually stick this in register D (for Drop):

[Zd!=r]sD

and then I can run

lDx
Parks answered 17/4, 2015 at 3:37 Comment(2)
I don't agree with macroing this for the same reason I wouldn't agree with writing a C macro to, say, tell if a number is even. Sure you could do that but it's better to build a vocabulary of idioms. lDx is only two characters shorter than Zd!=z and you lose a register in the process. Not worth it IMO.Pomerania
That's certainly a choice you can make. For anyone wanting to not use the register for a macro, feel free to not assign it to a register and type out the full 5 chars instead of 3. It works both ways. The answer is written in a way to present the direct answer to the question (Zd!=r) as well as what I personally do with that answer (put it in D).Parks

© 2022 - 2025 — McMap. All rights reserved.