Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate a Vector of Identical Items of Length N

Tags:

clojure

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}]
like image 869
zach Avatar asked Oct 24 '25 18:10

zach


2 Answers

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"]
like image 85
Leonid Beschastny Avatar answered Oct 27 '25 00:10

Leonid Beschastny


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"]
like image 40
Arthur Ulfeldt Avatar answered Oct 27 '25 00:10

Arthur Ulfeldt