Visit the reverse-string exercise on Exercism to read the full instructions and download the exercise files.
Dig Deeper
StringBuilder
String builder
(defn reverse-string [s]
(.toString
(.reverse
(StringBuilder. s))))
In Clojure, as in Java, strings are immutable.
It means that with every change we want to make to any string, we create a new string in memory.
String recreation can be very resource-intensive, especially when new strings are created in many steps.
This is a common problem, so Java provides the StringBuilder class, which holds characters as a collection,
allowing for modifications until we are ready to create the string by calling toString() method.
String builder has a built-in reverse() method, which we can use as shown above.
The complete approach is to initialise a StringBuilder with the string we want to reverse.
Then reverse it, and finally convert it back to string.
The shortcut
Is accessing the underlying Java Virtual Machine and Java classes necessary?
Couldn’t we just use the clojure.string/reverse function instead?
We could! This is the alternative way to reverse a string:
(defn reverse-string [s]
(clojure.string/reverse s))
In fact, at some level, we could consider both approaches to be equivalent.
Let’s have a look at the implementation of the clojure.string/reverse function.
(defn ^String reverse
"Returns s with its characters reversed."
{:added "1.2"}
[^CharSequence s]
(.toString (.reverse (StringBuilder. s))))
While there is a little bit more going on in the syntax, at its core, it is the same as the code at the top of this approach.
Use the fact that a string is also a sequence
It’s a sequence
(defn reverse-string [string]
(apply str (reverse string)))
In Clojure, many functions that operate on sequences will automaticaly convert a string parameter into a sequence of characters.
This is because many core functions call seq on its arguments.
Also, “most of Clojure’s core library treats collections and sequences the same way”.
It follows that we can use any method to reverse a sequence or a collection to reverse a string.
There will be three stops in this group of approaches:
- Convert a string to a sequence or a collection. (Is usually implicit, part of the next step).
- Reverse the sequence or a collection.
- Convert the sequence of characters back into a string. (It has to be explicit).
Reversing
Here are a few options for reversing a sequence of characters.
(reverse s)
The above is self-explanatory.
(into () s)
This takes one character at a time from s and adds it to a sequence.
Because in Clojure, by default, new elements are added to the beginning of the list,
into reverses the characters at the same time as changing a string into an explicit sequence.
The more explicit verbose version of this operation could be something like this:
(reduce conj () s)
Converting back to a string
There are many options here, too.
(apply str (reverse s))
(reduce str (reverse s))
(clojure.string/join (reverse s))
A single step version
We also have an option to combine all three operations into a single function call:
(defn reverse-string [s]
(reduce #(str %2 %1) "" s))
Which one to use?
I’d suggest using the one that is the most readable to you.
Recursion
Recursion
(defn reverse-string [s]
(loop [s s acc ""]
(if (empty? s)
acc
(recur
(rest s)
(str (first s) acc)))))
It is not necessarily bad to use recursion as shown in the example above.
In fact, many other approaches use recursion behind the scenes as, for instance, clojure.string/join is implemented using recursion.
However, we should remember that strings are immutable, so code like the above will be inefficient.
Instead, we should consider using the StringBuilder in the recursive function. For example, like so:
(defn reverse-string [s]
(loop [s (into () s) sb (StringBuilder. "")]
(if (empty? s)
(.toString sb)
(recur
(rest s)
(-> sb (.append (first s)))))))
Source: Exercism clojure/reverse-string