2

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

3 Answers 3

5

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 '())

Sign up to request clarification or add additional context in comments.

2 Comments

I usually prefer the exit condition first, as I find it easier to read.
Another point of view could be having the return/exit case last as that is most people are used to when looking at some function code in other languages as well :)
1

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)))

Comments

-1

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)))))

1 Comment

Ankur response is better as (foo -1) returns []. Your version will cause a OOM in this case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.