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.

8 thoughts on “A Haskell Quine”

        1. 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!

  1. 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) "

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

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

Leave a Comment

Your email address will not be published.