如何以惯用的clojure方式重复n次?

Mat*_*ggs 34 clojure

在Ruby中,"str" * 3会给你"strstrstr".在Clojure中,我能想到的最接近的是,(map (fn [n] "str") (range 3))是否有更惯用的方法呢?

Joo*_*aat 57

这个怎么样?

(apply str (repeat 3 "str"))
Run Code Online (Sandbox Code Playgroud)

要不就

(repeat 3 "str")
Run Code Online (Sandbox Code Playgroud)

如果你想要一个序列而不是一个字符串.


Mau*_*ijk 38

还有一个使用协议的有趣选择:

(defprotocol Multiply (* [this n]))
Run Code Online (Sandbox Code Playgroud)

接下来扩展String类:

(extend String Multiply {:* (fn [this n] (apply str (repeat n this)))})
Run Code Online (Sandbox Code Playgroud)

所以你现在可以'方便'使用:

(* "foo" 3)
Run Code Online (Sandbox Code Playgroud)

  • 对于比clojure.contrib.string/repeat更歪曲的代码的+1 (2认同)
  • 有趣,但不要在家里这样做.:) (2认同)

col*_*inf 10

您还可以使用clojure.contrib.string中的repeat函数.如果使用require等将其添加到命名空间

(ns myns.core (:require [clojure.contrib.string :as str]))
Run Code Online (Sandbox Code Playgroud)

然后

(str/repeat 3 "hello")
Run Code Online (Sandbox Code Playgroud)

会给你

"hellohellohello"
Run Code Online (Sandbox Code Playgroud)


Jac*_*ski 10

只是为了抛出更多令人敬畏且充满希望的发人深省的解决方案.

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"
Run Code Online (Sandbox Code Playgroud)