I want to create a function that when you input a number say 5 it'll return a vector of all numbers from 1 to 5, ie [1 2 3 4 5]
So far I am at
(defn counter [number]
(let [x 1
result []]
(when (<= x number)
(conj result x)
(inc x))))
Right now it'll put 1 into the vector but I want to say now (inc x)
and run through again. Do I have to use recur?
Any help is much appreciated
There is a builtin function range
. To achieve your goal (vector of numbers from 1 to n inclusively) you can wrap it as follows:
(defn get-range [n]
(->> n inc (range 1) vec))
(get-range 5)
#=> [1 2 3 4 5]
Also, you can go and use iterate
function
(defn get-range [n]
(->> (iterate inc 1)
(take n)
vec))
Or use a loop:
(defn get-range [n]
(loop [m 1
res []]
(if (> m n)
res
(recur (inc m) (conj res m)))))