Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/clojure/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/229.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Clojure 生成长度为N的相同项的向量_Clojure - Fatal编程技术网

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