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.
Asked
Active
Viewed 634 times
7

Kate Gregory
- 18,808
- 8
- 56
- 85

Mark Harrison
- 297,451
- 125
- 333
- 465
-
1How can it be that something is on the stack, that you dont want? – hendrik Aug 08 '13 at 09:15
-
1@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. – Gareth Rees Dec 22 '13 at 23:32
1 Answers
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
- Start with item to remove.
Stack: [5]
- Duplicate top of stack.
Stack: [5,5]
- Pop top 2 and test if they are not equal:
5 != 5
Stack: []
- 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

James Andariese
- 527
- 3
- 9
-
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. – Braden Best Aug 11 '23 at 00:46