Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to repeat string n times in idiomatic clojure way?

Tags:

clojure

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?

like image 313
Matt Briggs Avatar asked Mar 25 '11 14:03

Matt Briggs


4 Answers

How about this?

(apply str (repeat 3 "str"))

Or just

(repeat 3 "str")

if you want a sequence instead of a string.

like image 164
Joost Diepenmaat Avatar answered Nov 15 '22 11:11

Joost Diepenmaat


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)
like image 41
Maurits Rijk Avatar answered Nov 15 '22 10:11

Maurits Rijk


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"
like image 14
Jacek Laskowski Avatar answered Nov 15 '22 10:11

Jacek Laskowski


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"
like image 10
colinf Avatar answered Nov 15 '22 12:11

colinf