Search code examples
forth

Implement SWAP in Forth


I saw that in an interview with Chuck Moore, he says:

The words that manipulate that stack are DUP, DROP and OVER period. There's no, well SWAP is very convenient and you want it, but it isn't a machine instruction.

So I tried to implement SWAP in terms of only DUP, DROP and OVER, but couldn't figure out how to do it, without increasing the stack at least.

How is that done, really?


Solution

  • You are right, it seems hard or impossible with just dup, drop, and over.

    I would guess the i21 probably also has some kind return stack manipulation, so this would work:

    : swap   over 2>r drop 2r> ;
    

    Edit: On the GA144, which also doesn't have a native swap, it's implemented as:

    over push over or or pop
    

    Push and pop refer to the return stack, or is actually xor. See http://www.colorforth.com/inst.htm