How to repeat string n times in idiomatic clojure way?
Solution 1
How about this?
(apply str (repeat 3 "str"))
Or just
(repeat 3 "str")
if you want a sequence instead of a string.
Solution 2
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)
Solution 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"
Solution 4
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"
Solution 5
Or use the repeat function that comes with clojure-contrib' string package. In that case you can use (clojure.contrib.string/repeat 3 "str") which results in "strstrstr".
Rinzler
I have experience in JSP/Java/Oracle, and ASP.net/C#/Sql Server. I am a rubyist, a clojurian, a rustacean, and work with rails professionally. I would consider myself a javascript programmer, and my expertise is front end web development. I am also a big fan of both emacs and parts of vim. You can read my blog at http://mattbriggs.net
Updated on June 26, 2022Comments
-
Rinzler almost 2 years
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? -
Rinzler about 13 yearsperfect! I knew there had to be something like repeat, just couldnt find it
-
Joost Diepenmaat about 13 years+1 for code that's an order of magnitude more perverted than clojure.contrib.string/repeat :)
-
Eric Wilson over 11 yearsThis seems really useful, but it seems that it no longer exists. Do you know of a way to do this with Clojure 1.4?
-
David J. over 10 yearsFun, but don't do this at home. :)
-
Patrick almost 10 years@EricWilson clojure.contrib was mostly migrated to other places at the beginning of language version 1.3. clojure.contrib.string was migrated to clojure.string which does not appear to contain 'repeat' any longer.
-
Andrea Richiardi over 8 yearsI would also add then:
(clojure.string/join (repeatedly 3 (partial str "str")))
. Similar but different to the first one. -
Lassi over 5 yearsDoes
apply
hit a limit on the argument count if you have lots of repetitions?