我想根据项目和计数生成相同项目的向量.这似乎是一个比循环更容易做的事情.任何使功能更紧凑/精简的想法?
;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}]
Run Code Online (Sandbox Code Playgroud)
有一个内置函数重复,专门为这种情况设计:
> (repeat 5 "A")
("A" "A" "A" "A" "A")
Run Code Online (Sandbox Code Playgroud)
如您所见,它产生一系列相同的元素.如果你需要一个向量,你可以用vec转换它:
> (vec (repeat 5 "A"))
["A" "A" "A" "A" "A"]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
386 次 |
| 最近记录: |