Monday, May 22, 2006

Visual Basic Self-Replicator

I am reading Introduction to the Theory of Computation. In the chapter about advanced topics in computability theory, it mentioned a technique for building a self-replicating Turing machine (a Turing machine that writes its own description on its tape). I have implemented this basic technique to write a self-replicating program using Visual Basic 6 (a program that outputs its own code). [In the form designer, create one TextBox called Text1 and set its Multiline property to True.]

Private Sub Form_Load(): Text1.Text = "Private Sub X(): Text1.Text = ""Private Sub Form_Load(): Text1.Text = """""" + Replace(Text1.Text, """""""", """""""""""") + """""": X: End Sub"" + vbCrLf + vbCrLf + Text1.Text: End Sub": X: End Sub

Private Sub X(): Text1.Text = "Private Sub Form_Load(): Text1.Text = """ + Replace(Text1.Text, """", """""") + """: X: End Sub" + vbCrLf + vbCrLf + Text1.Text: End Sub

Here is a rough overview of how it works. X() is just a subroutine to take the contents of Text1, and output the code for a Form_Load function that would write those contents to Text1, followed by a blank line, followed by the previous contents of Text1. Form_Load() is the block that executes first. It simply transcribes the code of X() into Text1, then calls X(). I have a hard time keeping this all in my head at once.

This took me an hour to write, and had many more complications than I expected. It was difficult to accurately reproduce the double-quote character (") as it is used in the code. The syntax for escaping the double-quote in a string literal is to write two consecutive double quotes (""). Notice that at one point, I have written twelve consecutive double-quote characters. That was probably the highlight.

No comments: