[Clojure Solution]: Reverse word in a sentence

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?

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store