0
votes

Hi i am new to clojure i have written this function and there are few errors in it. i have got one function called 'checkFunction' it basically gets one paramtere and returns either true or false.

(defn getList [number1 number2]
  (loop for x from number1 to number2
    (recur (inc num) (if (checkFunction? x) (concat p [num]) p))))

i want the function above to take two paramters for example if i say 'get List 15 20' it should call check function with 15 16 17 18 19 20 and if checkFunction returns true it should put that number in the vector and return it or print it. so far i have got onto this but i am struggling a bit.

Any help or right direction would be very thankful.

1

1 Answers

0
votes

If I understand your question, you're trying to filter a range of numbers according to some predicate. (For the sake of the example I set your check-function? to return true for odd numbers.)

(defn check-function? [n]
  (odd? n))

(defn get-list [n1 n2]
  (filter check-function? (range n1 (+ 1 n2))))

> (get-list 15 20)
(15 17 19)

If you are also interested in how the loop-recur works, here's a version more like what you were trying to do originally. But I will say that one of the nicest things about clojure is that you rarely have to do this!

(defn get-list-2 [n1 n2]
  (loop [src (range n1 (+ 1 n2)) dest []]
    (if (empty? src)
      dest
      (let [n (first src)
            src (rest src)
            dest (if (check-function? n) (conj dest n) dest)]
        (recur src dest)))))

> (get-list-2 15 20)
[15 17 19]