Hacker News new | ask | show | jobs
by LandR 2244 days ago
The clojure one to reverse a string makes it a sequence of characters, then reverses that sequence and puts it back together again as a string..

Why not jsut:

     (require '[clojure.string :as str])
     (let [s "hello"]
         (str/reverse s))
     => "olleh"
Reversing a string is in the core library...
2 comments

Well, clojure.string/reverse is relying on StringBuilder so I guess you could call it not just Clojure but Clojure + Java really. Source for clojure.string/reverse is this: `(.toString (.reverse (StringBuilder. s))))`

(The implementation of clojure.string/reverse) would only work on Clojure running on JVM. Clojure-clr, ClojureScript or any of the other ones, would use a difference implementation, not using StringBuilder. `(apply str (reverse s))` is then I guess "more" general across Clojure implementations. So Clojure is using StringBuilder, ClojureScript is using regexes + split to list + reverse + rejoin, ClojureCLR I'm not sure, but probably something C# specific.

But in the end, that's all semantics and the point is moot. Since Clojure is a pragmatic language, using an already defined function is obviously better, so no reason why you wouldn't use clojure.string/reverse, all the Clojure implementations have it exposed already.

On a related note, the problem is underspecified.

> Create string t containing the same characters as string s, in reverse order. Original string s must remain unaltered. Each character must be handled correctly regardless its number of bytes in memory.

What encoding? Assuming UTF-8, what is a "character"? A code point? A grapheme? The result of the lack of specification is that the different approaches really solve different problems. Some, like the C implementation, have a naive approach that only solves the problem in fixed size encodings where the width is equal to CHAR_BIT. Others I'm sure run into problems with combining characters

Submit a task/"idiom" with an improved/stricter spec and link back to the original one.