Implementing SWAP in Fort

I saw in an interview with Chuck Moore he says:

The words that manipulate this stack are the DUP, DROP, and OVER periods. There, good SWAP is very convenient, and you want it, but this is not a machine instruction.

Therefore, I tried to implement SWAP only with DUP , DROP and OVER , but could not figure out how to do this without increasing at least the stack.

How is this done, really?

+7
forth
source share
2 answers

You are right, it seems difficult or impossible only with dup, drop and over.

I would suggest that i21 probably also has some kind of reverse stack manipulation, so this would work:

 : swap over 2>r drop 2r> ; 

Edit: on GA144, which also does not have its own swap, it is implemented as:

 over push over or or pop 

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

+7
source share

At Standard Forth it

 : swap ( ab -- ba ) >r >r 2r> ; 

or

 : swap ( ab -- ba ) 0 rot nip ; 

or

 : swap ( ab -- ba ) 0 rot + ; 

or

 : swap ( ab -- ba ) 0 rot or ; 
+3
source share

All Articles