Uncle Aaroh
Uncle Aaroh

Reputation: 831

How do i get the tail from the recursive function which is building a list of results?

Currently the following code is returning a list from 2-10 when i pass the number 2. I don't want it to return first element 2 in the list.

boot.user=> (defn hierarchy [num]
#_=>   (when num
#_=>     (lazy-seq (cons num (hierarchy (#(when (< % 10) (inc %)) num))))))
#'boot.user/hierarchy

boot.user=> (hierarchy 2)
(2 3 4 5 6 7 8 9 10)

Expected result is

(3 4 5 6 7 8 9 10)

I know if i call the rest function i will get the tail but i couldn't think of a better refactor of this function to give me back only tail.

Upvotes: 0

Views: 47

Answers (1)

leetwinski
leetwinski

Reputation: 17859

first of all i would rewrite your function this way for the sake of readability:

(defn hierarchy [num]
  (when (< num 10)
    (lazy-seq (cons num (hierarchy (inc num))))))

user> (hierarchy 3)
;;=> (3 4 5 6 7 8 9 10)

then you could abstract the recursion to the inner function, while the outer would do the first increment:

(defn hierarchy [num]
  (letfn [(h-inner [num] (when (< num 10)
                           (lazy-seq (cons num (h-inner (inc num))))))]
    (h-inner (inc num))))

user> (hierarchy 3)
;;=> (4 5 6 7 8 9 10)

also this task is best solved with range or maybe iterate, but i guess it is an educational example to practice the recursion.

Upvotes: 2

Related Questions