#908 Quine - Fantom code printing its source (fun topic)

katox Wed 13 Jan 2010

I got distracted by today's xkcd so I made a fantom onliner version of the popular quine riddle

class Q{static Void main(){s:="class Q{static Void main(){s:=;c:=34.toChar;echo(s[0..<30]+c+s+c+s[30..-1]);}}";c:=34.toChar;echo(s[0..<30]+c+s+c+s[30..-1]);}}

If anyone had a more "fantomy" version I'd like to see it of course ;)

DanielFath Thu 14 Jan 2010

I've got one, only prettier format though.

class Q
{
  static Void main()
  {
    s:="""class Q
          {
            static Void main()
            {
              s:=;
              c:=34.toChar;
              o:="          ";
              echo(s[0..<42]+c+c+c+s[0..<8]+o+s[8..<10]+o+s[10..<31]+o+s[31..<35]+o+s[35..<45]+o+s[45..<66]+o+s[66..<83]+o+s[83..241]+o+s[242..-6]+o+s[ -5..-2]+o+s[-3..-3]+c+c+c);
              echo(s[46..<62]+s[64..<83]+s[-128..-57]+s[-58..-6]+s[-5..-1]);
            }
          }"""
    c:=34.toChar;
    o:="          ";
    echo(s[0..<42]+c+c+c+s[0..<8]+o+s[8..<10]+o+s[10..<31]+o+s[31..<35]+o+s[35..<45]+o+s[45..<66]+o+s[66..<83]+o+s[83..252]+o+s[253..-6]+o+s[ -5..-2]+o+s[-3..-3]+c+c+c);
    echo(s[44..<62]+s[62..<83]+s[-242..-57]+s[-58..-6]+s[-5..-1]);
  }
}

katox Thu 14 Jan 2010

Nice ;), I got some minor differences when running the sample though

$ fan danielFath.fan > q && diff -ud danielFath.fan  q

It seems that some indices are off.

DanielFath Thu 14 Jan 2010

Facepalm. They aren't. If you look at the code I pasted you'll see the last command is echo(size), which I used to get the size as the string changed.

Fixed it now :D

Now we should optimize! Reminds me of an article I read when people tried to write the shortest self-replicating code.

katox Thu 14 Jan 2010

Multi-line version with improved readability

class Q
{
  static Void main()
  {
    r := "class Q\n{\n  static Void main()\n  {\n    r := "
    s := "\n    s := \n    echo (r+r.toCode+s[0..9]+s.toCode+s[10..-1])\n  }\n}"
    echo (r+r.toCode+s[0..9]+s.toCode+s[10..-1])
  }
}

It is probably nicer but not shorter than the first sample:

$ wc oneliner.fan quine.fan 
  1   7 159 oneliner.fan
  9  31 231 quine.fan

i.e. 72 characters more. But cut'n'paste is definitely easier too! ;)

DanielFath Thu 14 Jan 2010

class QuineFile
{
  Void main()
  {
    file := `./QuineFile.fan`.toFile
    echo(file.readAllStr)
  }
}

I cheated :P (Gogo.. plumber programming). The expression could have been shorter if Fan supported relative paths :( or at least current directory.

  • Characters (no spaces): 79
  • Characters (with spaces): 90

brian Thu 14 Jan 2010

The expression could have been shorter if Fan supported relative paths :( or at least current directory.

You can use relative paths

fansh> `./`.toFile.list

DanielFath Thu 14 Jan 2010

Upps. My mistake. In my defense I tried //., /.. and /. but they didn't work.

Login or Signup to reply.