online advertising

Monday, February 27, 2017

Recursion Theorem in Practice - building a quine in C#

The goal of this post is to share my experience building a C# program that output its own source. This is often known as a quine.

According to the recursion theorem, a Turing machine can reference its own representation. So a quine, if built, serve as an example to show recursion theorem is true in this case.

Without further ado, here is the C# program I built. It can generate it an identical copy of its own source code to the console.

class Program
{
    static void Main()
    {
        string tape = @"        string a = @""class Program
{
    static void Main()
    {
        string tape = @"""""" + tape.Replace(""\"""", ""\""\"""") + @"""""";
"";
        System.Console.WriteLine(a + tape);
    }
}";
        string a = @"class Program
{
    static void Main()
    {
        string tape = @""" + tape.Replace("\"", "\"\"") + @""";
";
        System.Console.WriteLine(a + tape);
    }
}

The coloring is intended to show how this quine is constructed. The red part of the program is intended to construct the blue part of the program. In fact, the whole highlighted part in the red program is really just a string literal that is the same as the blue part. Therefore the definition of the red part depends on the blue part.

Now the blue part must construct the red part and concatenate them together. But we have a small problem here. The blue part's definition cannot depend on the red part's, otherwise we have a dependency cycle. The key is that we compute the red part instead. That is why we used three strings to compute a variable named a, and once we get the red part, we get the blue part from the tape variable, and therefore we completed constructing the whole source code, now we output it!

Try to run the program and use a diff tool to compare the source code, they are identical! Not a space is missing!

No comments :

Post a Comment