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 Comments
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) "
Thanks! This is perhaps the shortest I have ever seen. :)
Assuming visibility of Control.Monad and Control.Monad.Reader, one can abbreviate further to
main=liftM2(>>)putStr print"main=liftM2(>>)putStr print"main=putStr (a++show a) where a="main=putStr (a++show a) where a="Oops, please delete parent comment. Nothing new, nothing interesting.
which is still not as short as
main=(putStr.ap(++)show)"main=(putStr.ap(++)show)"that can be found here
Which can be slightly improved to
main=putStr.ap(++)show$"main=putStr.ap(++)show$"
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!