15 May 2012

Erlang Quine

I'm just getting started with Erlang. Naturally, after writing "Hello, world!" the next program I wrote was a Quine:
-module(q).
-export([main/0]).

main() ->
A="-module(q).\n-export([main/0]).\n\nmain() ->\n",
B="io:format(\"~sA=~p,~nB=~p,~n~s\",[A, A, B, B]).",
io:format("~sA=~p,~nB=~p,~n~s",[A, A, B, B]).
Erlang's "pretty print" formatting code makes this super easy. In particular, no raw ASCII codes necessary here!

Update: OK, after thinking more about it, it can be a little simpler:
-module(r).
-export([main/0]).

main() ->
 Fmt = "-module(r).\n-export([main/0]).\n\nmain() ->\n Fmt = ~p,\n io:format(Fmt, [Fmt]).\n",
 io:format(Fmt, [Fmt]).

No comments:

Post a Comment