Repeating Digits in Clojure

My son asked me if I could make the computer double numbers, like
2 4 6 → 22 44 66
I started with a really ugly solution:
(map
(fn [x]
(parse-long (clojure.string/join
""
[(str x) (str x)])))
[2 4 6])
;;=> (22 44 66)
I wanted to see how ChatGPT could improve my answer. Here’s what it came up with:
(map
#(parse-long (format "%d%d" % %))
[2 4 6])
This is really elegant. I’ve used format strings extensively in C, C#, F#, Clojure, and a handful of other languages I don’t know very well, but I never thought about putting the same value in a format string more than once.
;; Of course
(#(format "%d%d" %1 %2) 2 2)
;;=> "22"
;; Wow, never thought of it like this
(#(format "%d%d" %1 %1) 2)
;;=> "22"
Here’s a second solution ChatGPT came up with:
(map
#(parse-long (str % %))
[2 4 6])
Bravo! I felt extra silly with my clojure.string.join after seeing this. I forgot str is multi-arity with a variadic arity. I also didn’t know it had a 0-arity. Here’s the actual implementation:
(defn str
"With no args, returns the empty string. With one arg x, returns
x.toString(). (str nil) returns the empty string. With more than
one arg, returns the concatenation of the str values of the args."
{:tag String
:added "1.0"
:static true}
(^String [] "")
(^String [^Object x]
(if (nil? x) "" (. x (toString))))
(^String [x & ys]
((fn [^StringBuilder sb more]
(if more
(recur (. sb (append (str (first more)))) (next more))
(str sb)))
(new StringBuilder (str x)) ys)))
Here’s a third solution from ChatGPT. I quite like it:
(for [n [2 4 6]]
(parse-long (str n n)))
I almost never use for, but I should. It’s pretty amazing!
I didn’t want to be bested by the LLM, so i came up with another solution using repeat:
(map #(apply str (repeat 2 %)) [2 4 6])
One benefit of this solution is the ability to parameterize the repetitions. For example, if I wanted to repeat the digit five times instead of twice:
(let [repetitions 5]
(map
#(apply str (repeat repetitions %))
[2 4 6]))
;;=> ("22222" "44444" "66666")




