I would like to generate a vector of identical items given the item and a count. This seems like a something that should be easier to do than with a loop. Any ideas of making the function below tighter/streamlined?
;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}]
There is a build-in function repeat designed especially for this case:
> (repeat 5 "A")
("A" "A" "A" "A" "A")
As you can see, it produce a sequence of identical elements. If you need a vector, you may conver it with vec:
> (vec (repeat 5 "A"))
["A" "A" "A" "A" "A"]
The repeat function come in handy here:
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"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With