A quine in Clojure

Sergii Riabokon
1 min readJan 11, 2023

--

There is an interesting logical exercise in programming called implementing a quine (pronounced as ‘kwain’) program.

A quine is a program that outputs its code listing to the screen without using any File IO operations from the language system. It is a actually interesting paradox resembling fractals in mathematics. Jon von Neumann was the first one who wrote about possibility of a such algorithm.

Here is my implementation of a quine in Clojure (popular dialect of Lisp).

A bit tricky. The general idea is:

  • to pass helping characters like quotes, brackets as a parameters to function in its arguments;
  • two constants are defined with let expression prefix and sufix;
  • first part of program is saved to a constant prefix;
  • prefix is send two times to output by a println;
  • sufix constant holds the code of println;
  • calling of the fn1 function is constructed with indirect use of brackets, spaces from a functions arguments.

After saving it to a file quine.clj, run:

> clj quin.clj -M fn1

As a result it outputs its own code to the screen. Alternatively possible to redirect to a file and use cmp to catch the difference

> clj quine.clj -M fn1 > quine2.clj
> cmp quine.clj quine2.clj

No difference found in files quine.clj and quine2.clj files.

--

--

Sergii Riabokon
Sergii Riabokon

Written by Sergii Riabokon

Technical blog about programming and related stuff. Mostly contains my personal discoveries and some memorable notes.

No responses yet