How to write a program that can replicate itself
Grotsky is a toy programming language that I made for fun. Today we're visinting the concept of Quines, a.k.a. self replicating programs. It's said that any turing-complete language should be able to write a program that replicates itself. And grotsky is no exception.
Read more about grotsky in previous blogposts:
- Grotsky Part 1: Syntax
- Grotsky Part 2: Parsing expressions
- Grotsky Part 3: Interpreting
- Grotsky Part 4: Writing a service to get your public IP
- I created a programming language and this blog is powered by it
Quines are very easy to write. The language that you're using needs to be able to do a couple things:
- Write to a file or stdout (print)
- Support for string arrays
- Translate numbers/integers to character ascii representation
- Concatenate strings
- Loop through arrays from arbitrary indexes
Super simple quine: less than 30 lines of code
let tabChar = 9 let quoteChar = 34 let commaChar = 44 let code = [ "let tabChar = 9", "let quoteChar = 34", "let commaChar = 44", "let code = [", "]", "for let i = 0; i < 4; i = i+1 {", " io.println(code[i])", "}", "for let i = 0; i < code.length; i = i+1 {", " io.println(strings.chr(tabChar) + strings.chr(quoteChar) + code[i] + strings.chr(quoteChar) + strings.chr(commaChar))", "}", "for let i = 4; i < code.length; i = i+1 {", " io.println(code[i])", "}", ] for let i = 0; i < 4; i = i+1 { io.println(code[i]) } for let i = 0; i < code.length; i = i+1 { io.println(strings.chr(tabChar) + strings.chr(quoteChar) + code[i] + strings.chr(quoteChar) + strings.chr(commaChar)) } for let i = 4; i < code.length; i = i+1 { io.println(code[i]) }
Now we can use grotksy cli to run the program and compare the output to the original source.
Save the original source to a file called quine.gr then run the following commands:
$ grotsky quine.gr > quine_copy.gr $ cmp quine.gr quine_copy.gr $ echo $? 0
If you see a 0 as the final output that means the files are the same. Otherwise if you saw an error message or a different output, that means something has gone wrong.
How exciting is this?!! We've just written a program that gives itself as an output. That sounds impossible when you hear it for the first time. But it was actually pretty easy!
Source code available here: https://gist.github.com/mliezun/c750ba701608850bd86d646a3ebf700f.
Grotsky cli binary available here: https://github.com/mliezun/grotsky/releases/tag/v0.0.6