生成长度为N的相同项的向量

时间:2013-12-11 23:41:52

标签: 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-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}]

3 个答案:

答案 0 :(得分:8)

有一个内置函数repeat专为这种情况设计:

> (repeat 5 "A")
("A" "A" "A" "A" "A")

如您所见,它产生了一系列相同的元素。如果您需要矢量,可以使用vec

进行转换
> (vec (repeat 5 "A"))
["A" "A" "A" "A" "A"]

答案 1 :(得分:1)

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"]

答案 2 :(得分:1)

user> (into [] (repeat 5 "A"))
["A" "A" "A" "A" "A"]

user> (into [] (repeat 3 {:years 3}))
[{:years 3} {:years 3} {:years 3}]