[Clojure Solution]: Reverse word in a sentence

Racheal Mwatela
1 min readJan 19, 2021

So I came across this basic coding challenge

Reverse the words in a sentence — i.e., “My name is Martha” becomes “Martha is name My.”

For a second I thought of using loops because that is what hits me right away but after a couple of tries and with no luck, I decided to try it differently.

This one is more readable and optimized compared to how I could have written it with a loop. It took less time as well!

=> (def s "My name is Martha")=> (defn generate-reversed-string [s]        (->> (clojure.string/split s #" ")             reverse             (interpose " ")             (apply str)))=> (generate-reversed-string s)

Here is how I worked through it :

  1. I split the string where there are white spaces. The split function returns a vector of the strings split i.e [“My” “name” “is” “Martha”]
  2. `Reverse` will reverse the order of items but this returns a sequence which we need to convert back into a string.
  3. To do this, we separate the sequence with quotes then apply str function

I got to achieve what I want with this simple Clojure solution but I would like to know how would you have done it differently?

--

--

Racheal Mwatela

Hey, I am a Software Engineer with a passion for mentorship and career development