In Ruby, "str" * 3
will give you "strstrstr". In Clojure, the closest I can think of is (map (fn [n] "str") (range 3))
Is there a more idiomatic way of doing it?
How about this?
(apply str (repeat 3 "str"))
Or just
(repeat 3 "str")
if you want a sequence instead of a string.
And one more fun alternative using protocols:
(defprotocol Multiply (* [this n]))
Next the String class is extended:
(extend String Multiply {:* (fn [this n] (apply str (repeat n this)))})
So you can now 'conveniently' use:
(* "foo" 3)
Just to throw some more awesome and hopefully thought-provoking solutions.
user=> (clojure.string/join (repeat 3 "str"))
"strstrstr"
user=> (format "%1$s%1$s%1$s" "str")
"strstrstr"
user=> (reduce str (take 3 (cycle ["str"])))
"strstrstr"
user=> (reduce str (repeat 3 "str"))
"strstrstr"
user=> (reduce #(.concat %1 %2) (repeat 3 "str"))
"strstrstr"
You could also use the repeat function from clojure.contrib.string. If you add this to your namespace using require such as
(ns myns.core (:require [clojure.contrib.string :as str]))
then
(str/repeat 3 "hello")
will give you
"hellohellohello"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With