在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)
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)
| 归档时间: |
|
| 查看次数: |
8996 次 |
| 最近记录: |