Use the fact that a string is also a sequence

Reverse String
Reverse String in Clojure
(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:

  1. Convert a string to a sequence or a collection. (Is usually implicit, part of the next step).
  2. Reverse the sequence or a collection.
  3. 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.

13th Nov 2024 · Found it useful?