How to repeat string n times in idiomatic clojure way?

前端 未结 7 2238
无人及你
无人及你 2020-12-15 16:13

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 idioma

7条回答
  •  既然无缘
    2020-12-15 16:55

    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"
    

提交回复
热议问题