Introduction to Code-Golf in Clojure
Code-Golf is the art of writing the shortest program in a given language that implements some given algorithm. It started in the 90’s in the Perl community and spread to other languages; there are now languages dedicated to code-golfing and StackExchange has a Q&A website for it.
4clojure is a well-known website to learn Clojure through exercises of increasing difficulty, but it has a lesser-known code-golf challenge which you can enable by clicking on “Leagues” in the top menu. If you check the code-golf checkbox, you then get a score on each problem that is the number of non-whitespace characters of your solution; the smaller the better.
The first thing you’ll note when code-golfing is that the reader syntax for
anonymous functions is a lot shorter than using
Unfortunately you can’t have a reader-syntax function inside another reader-syntax one, so you often have to transform the code not to use anonymous functions.
for is a very powerful tool for that, because it allows you to do the
map, and a lot more, with no function:
On some problems it can even be shorter than using
Some core functions are equivalent in some contexts and so the shorter one can substitute a longer one:
When you must use a long function name in multiple places, it might be shorter
let that function with a one-letter symbol:
Use indexed access on vectors:
Use set literals as functions:
Inverse conditions to use shorter functions:
Inlined code is sometimes shorter:
1 instead of
Use maps instead of
ifs for conditions on equality (this one really makes
the code harder to read):