murtaza52
murtaza52

Reputation: 47441

recursion in clojure

I am trying to make this sample program work

(defn foo
  ([x] (foo x []))
  ([x current]
     (when (> x 0)
       (recur (dec x) (conj current x)))))

When I call this function (foo 5), I should get [1 2 3 4 5], however it only returns nil. What am I doing wrong?

Thanks, Murtaza

Upvotes: 2

Views: 339

Answers (3)

number23_cn
number23_cn

Reputation: 4629

I have corrected your original program to use (if (= x 0) instead of (when (> x 0), and this returns [1 2 3 4 5].

(defn foo
  ([x] (foo x []))
  ([x current]
     (if (= x 0)
       (apply vector (sort < current))
       (recur (dec x) (conj current x)))))

Upvotes: -1

murtaza52
murtaza52

Reputation: 47441

The code below works. I was not returning the final value.

(defn foo
  ([x] (foo x []))
  ([x current]
     (if (> x 0)
       (recur (dec x) (conj current x))
       current)))

Upvotes: 1

Ankur
Ankur

Reputation: 33657

Your recursion doesn't have a return expression i.e when then when is false the recursion terminates and it returns nil. You can fix this using if as:

(defn foo
  ([x] (foo x []))
  ([x current]
     (if (> x 0)
       (recur (dec x) (conj current x))
       current)))

This will return [5 4 3 2 1] for (foo 5) as you are using vector as return value and conj on vector appends the item at the end of the vector. You can either reverse the vector or use list i.e in place of (foo x []) use (foo x '())

Upvotes: 5

Related Questions