Log in

No account? Create an account
penrose orange



cat /var/log/stephen >/dev/eyes

Fun with stacks
penrose orange
Some stack operations can be simulated with combinations of other operations. Here's how to make swap using over, tuck and xor
rpn> 63 27 over xor tuck xor tuck xor .s
27 63

(I got the idea for that one as I was entering the office this morning. I worked it out on paper when I got a bit stuck with my work this morning!) Most programmers are probably familiar with the xor trick to swap two ints without using a temporary variable. over and tuck are from Forth: over copies the penultimate stack value onto the top of the stack; tuck copies the value on the top of the stack, placing it under the penultimate value.

The heap can be used to simulate stack operations too, as long as you don't mind overwriting the contents of heap cells. drop can simply be simulated as a store to any location. dup can be implemented as a store followed by two loads. Even without a heap, some stack operations can be implemented very simply in terms of others. drop can be replaced with 0 +, for example.

I wonder what the minimum stack operations are for a viable stack machine?