Clojure 生成长度为N的相同项的向量
我想在给定项目和计数的情况下生成相同项目的向量。这似乎比使用循环更容易实现。有没有让下面的功能更紧凑/精简的想法Clojure 生成长度为N的相同项的向量,clojure,Clojure,我想在给定项目和计数的情况下生成相同项目的向量。这似乎比使用循环更容易实现。有没有让下面的功能更紧凑/精简的想法 ;take an object and a nubmer n and return a vector of those objects that is n-long (defn return_multiple_items [item number-of-items] (loop [x 0 items [] ] (if (= x number-
;take an object and a nubmer n and return a vector of those objects that is n-long
(defn return_multiple_items [item number-of-items]
(loop [x 0
items [] ]
(if (= x number-of-items)
items
(recur (+ x 1)
(conj items item)))))
>(return_multiple_items "A" 5 )
>["A" "A" "A" "A" "A"]
>(return_multiple_items {:years 3} 3)
>[{:years 3} {:years 3} {:years 3}]
有一个专门为这种情况设计的内置功能:
> (repeat 5 "A")
("A" "A" "A" "A" "A")
如您所见,它产生了一系列相同的元素。如果您需要向量,可以使用以下方法转换:
repeat
功能在这里派上了用场:
user> (defn return-multiple-items [item how-many]
(vec (repeat how-many item)))
#'user/return-multiple-items
user> (return-multiple-items "A" 5)
["A" "A" "A" "A" "A"]
这正是我想要的。我在clojure文档上翻了一会儿,找不到我要找的东西。谢谢
user> (defn return-multiple-items [item how-many]
(vec (repeat how-many item)))
#'user/return-multiple-items
user> (return-multiple-items "A" 5)
["A" "A" "A" "A" "A"]
user> (into [] (repeat 5 "A"))
["A" "A" "A" "A" "A"]
user> (into [] (repeat 3 {:years 3}))
[{:years 3} {:years 3} {:years 3}]