This week’s challenge was to reverse a string. And I took the “Indiana Jones when that guy waves the sword around and Indy just shoots him” approach this week and got the silver medal using three languages that make this exercise a one-liner.
Clojure
First up, Clojure:
(ns reverse-string)
(defn reverse-string [s] ;; <- arglist goes here
(clojure.string/reverse s)
)
Haskell
Next Haskell:
module ReverseString (reverseString) where
reverseString :: String -> String
reverseString str = reverse str
JavaScript
And finally, Javascript.
export const reverseString = (word) => {
return word.split("").toReversed().join("");
};
(Why does this java script exercise go out of its way to avoid using the keyword function
?
I don’t know, that was part of the stub exercism provided…)
Comparison
While these three solutions all look pretty similar,
it’s kind of neat that they are, in fact, all doing something kind of different on some level.
The clojure approach uses a function that just reverses a string.
The javascript one turns the string into an array, reverses that and then turns it back into a string.
In Haskell, a string literally just is an array of characters,
so you are using the reverse
function that takes an array and outputs the reversed array.
I considered having a go at C++ or MIPS or something else where I would have to actually loop over the characters in reverse or some such, but decided I do not want to do that. There’s a lot of tricky business of deciding how big the units are that we ought to be looping over, once we leave ASCII-land. Here’s an interesting blog post about it. I decided that I very much did not want to spend my time doing it “right” for that bigger problem space. So there we go, Week 2 done in record time. I’d need to do C++ and Nim for the gold medal, and I have very little interest in learning either of those languages right now. So I’ll take my silver, thanks very much.