Skip to content

Instantly share code, notes, and snippets.

@coproduto
Last active October 10, 2022 17:45
Show Gist options
  • Save coproduto/98c898dadf67bb56057cfd023a6f46ad to your computer and use it in GitHub Desktop.
Save coproduto/98c898dadf67bb56057cfd023a6f46ad to your computer and use it in GitHub Desktop.
defmodule Quine do
@header "defmodule Quine do\n @header \""
@indent """
def indent(str) do
str
|> String.split(\"\\n\")
|> Enum.map(&(\" \" <> &1))
|> Enum.join(\"\\n\")
end
"""
@escape """
def escape(str) do
str
|> String.replace(\"\\\\\", \"\\\\\\\\\")
|> String.replace(\"\\\"\", \"\\\\\\\"\")
end
"""
@terminate """
def terminate(str) do
String.replace(str, ~r/$/, \"\\\"\\\"\\\"\\n\")
end
"""
@process """
def process(str) do
str
|> indent()
|> escape()
|> terminate()
end
"""
@run """
def run() do
IO.puts(@header <> \"defmodule Quine do\\\\n @header \\\\\\\"\\\"\")
IO.puts(\"\")
IO.puts(\" @indent \\\"\\\"\\\"\")
IO.puts(process(@indent))
IO.puts(\" @escape \\\"\\\"\\\"\")
IO.puts(process(@escape))
IO.puts(\" @terminate \\\"\\\"\\\"\")
IO.puts(process(@terminate))
IO.puts(\" @process \\\"\\\"\\\"\")
IO.puts(process(@process))
IO.puts(\" @run \\\"\\\"\\\"\")
IO.puts(process(@run))
IO.puts(\" @footer \\\"end\\\"\")
IO.puts(\"\")
IO.puts(@indent)
IO.puts(@escape)
IO.puts(@terminate)
IO.puts(@process)
IO.puts(@run)
IO.puts(@footer)
end
"""
@footer "end"
def indent(str) do
str
|> String.split("\n")
|> Enum.map(&(" " <> &1))
|> Enum.join("\n")
end
def escape(str) do
str
|> String.replace("\\", "\\\\")
|> String.replace("\"", "\\\"")
end
def terminate(str) do
String.replace(str, ~r/$/, "\"\"\"\n")
end
def process(str) do
str
|> indent()
|> escape()
|> terminate()
end
def run() do
IO.puts(@header <> "defmodule Quine do\\n @header \\\"\"")
IO.puts("")
IO.puts(" @indent \"\"\"")
IO.puts(process(@indent))
IO.puts(" @escape \"\"\"")
IO.puts(process(@escape))
IO.puts(" @terminate \"\"\"")
IO.puts(process(@terminate))
IO.puts(" @process \"\"\"")
IO.puts(process(@process))
IO.puts(" @run \"\"\"")
IO.puts(process(@run))
IO.puts(" @footer \"end\"")
IO.puts("")
IO.puts(@indent)
IO.puts(@escape)
IO.puts(@terminate)
IO.puts(@process)
IO.puts(@run)
IO.puts(@footer)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment