A Haskell Quine

A Haskell quine. That is, a program whose output is itself.


main = putStr (s ++ [';',' ','s',' ','=',' '] ++ show s);
s = "main = putStr (s ++ [';',' ','s',' ','=',' '] ++ show s)"

To deal with string quoting, it is difficult to write a quine not assuming a particular encoding (e.g. ASCII). In Haskell, however, it is side-stepped by using the built-in show function for strings. See also the quine page.

Functional programmers would notice that such programs resembles the lambda expression (\x -> x x) (\x -> x x), which reduces to itself. As a simple extension, this self-expanding program inserts to itself one line of empty comment each time it is run. It resembles the Y combinator.

Yokoyama later came up with a more elegant quine.

This entry was posted in Research Blog and tagged , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

8 Comments

  1. Posted May 5, 2010 at 6:34 am | Permalink

    Why not take advantage of the function print, which combines putStr (well, putStrLn really) and show ?


    main = putStr s >> print s
    s = "main = putStr s >> print s\ns = "

    Alternatively, one can combine this into a single statement:


    main = (\s -> putStr s >> print s) "main = (\\s -> putStr s >> print s) "

    • Posted May 6, 2010 at 9:57 am | Permalink

      Thanks! This is perhaps the shortest I have ever seen. :)

    • John Tromp
      Posted December 2, 2010 at 1:24 am | Permalink

      Assuming visibility of Control.Monad and Control.Monad.Reader, one can abbreviate further to

      main=liftM2(>>)putStr print"main=liftM2(>>)putStr print"

  2. red75
    Posted October 26, 2010 at 5:00 pm | Permalink

    main=putStr (a++show a) where a="main=putStr (a++show a) where a="

    • red75
      Posted October 26, 2010 at 5:13 pm | Permalink

      Oops, please delete parent comment. Nothing new, nothing interesting.

    • John Tromp
      Posted December 2, 2010 at 1:50 am | Permalink

      which is still not as short as
      main=(putStr.ap(++)show)"main=(putStr.ap(++)show)"
      that can be found here

      • John Tromp
        Posted December 2, 2010 at 1:56 am | Permalink

        Which can be slightly improved to


        main=putStr.ap(++)show$"main=putStr.ap(++)show$"

        • Posted December 10, 2010 at 3:57 pm | Permalink

          Thanks to both of you for submitting better quines (and sorry for slow response). I used to think that we need two kinds of quotes (” and ‘) to make it work. Obviously we do not!

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>