Heptic
Heptic

Reputation: 3106

Clojure tail call recursion with variable argument function

I basically want this:

(defn mymax
        ([a b] (if (> a b) a b))
        ([a b & rest] (apply recur (conj rest (mymax a b)))))

So that: (mymax 1 2 3 4) tail calls (mymax 2 3 4) which tail calls (mymax 3 4)

I see the problem that "apply" stops recur being in the tail position, which means it won't work. But I don't see how I can not use apply for variable arguement functions

[Note, I know you can solve this particular problem with reduce. Just wondering if you can do tail-call-recursion with variable params]

Upvotes: 4

Views: 801

Answers (1)

Ankur
Ankur

Reputation: 33657

Make the function take a single vector as an argument rather than using aruguments as the sequence of values. That would allow you to get rid of apply.

(defn mymax [[a b & rest]]
  (let [m (if (> a b) a b)]    
    (if (not rest)
        m 
        (recur (conj rest m)))))

Upvotes: 7

Related Questions