APL (Dyalog Classic), 4650 bytes
T←{(⍺⍺2↑⍵),2↓⍵}
p←+/T
m←¯1∘⊥T
x←⊃,⊢
s←⌽T
d←1∘↓
⎕←⎕
- Programs start on the right with
⍬
(empty array, called zilde) and run as their own lines, not as strings. n,
pushesn
onto the stack.p
adds the top two.m
subtracts the top from the second.x
duplicates the top.s
swaps the top two.d
drops the top.
Note that the spaces are necessary.
Polish notation is used, i.e. read right-to-left (opposite of the examples in the question), as APL itself is right-to-left.
The stack is stored and displayed top-to-bottom (opposite of the examples in the question).
E.g. using Polish notation 1 dup 2 +
becomes p 2,x 1,⍬
and outputs 3 1
My first time using dops (user-defined operators) in APL. Doesn't seem too useful for golfing, unless you are defining multiple similar functions. T
is a dop defined as {(⍺⍺2↑⍵),2↓⍵}
. This is a monadic operator that takes a monadic function on the left, and applies it to the first two elements of the array on the right, then catenates with the rest of the array (you can even use this to define new stack operations).
Would love to know how this can be improved upon.
EDIT: There was a bug in my minus function that would negate the whole stack. None of the test cases noticed it though. Fixed now but had to add one byte.