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 :
- 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”]
- `Reverse` will reverse the order of items but this returns a sequence which we need to convert back into a string.
- 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?