A Quine in Forth
Originally published on: Tue, 04 Aug 2009
I needed a little mental exercise tonight, so I chose to write a quine ( a program that produces its own source as its output ) in the Forth programming language?
Why Forth? Because I’m a novice Forth programmer at best. I don’t think very well in Forth, so this took some effort. Here’s the quine: ( the source for this quine is in the public domain )
s" swap dup 1 type 34 emit 32 emit over over swap type 34 emit 32 emit swap type" swap dup 1 type 34 emit 32 emit over over swap type 34 emit 32 emit swap type
I tested the above in immediate mode in Win32Forth and an online version of GForth (v0.7.3).
The first portion:
s" … to the ending " leaves the address and length of a counted string on the stack. By following that with swap dup 1, I was able to make a counted version of the string with a length of 1. A call to the type word then displays the letter “s” from the beginning of the string “swap”.
emit 34 emit 32 causes a double-quote and a space to appear. So, the only thing I have left to do is to display the string, a dquote and the string again and I’m done.
I do that by using the remaining code over over swap type 34 emit 32 emit swap type.