Fork me on GitHub

Working with Joy of Clojure and I can't get the xconj function there to work. Anyone who can spot what is wrong here: tree1 evaluates to nil..

(defn xconj [t v]
    (nil? t) {:val v, :L nil, :R nil}
    (< v (:val t)) {:val (:val t)
                    :L (xconj (:L t) v)
                    :R (:R t)}))

(def tree1 (xconj nil 5))
(def tree1 (xconj tree1 3))
(def tree1 (xconj tree1 8))


Alex Miller (Clojure team)12:10:42

There's only 2 cases in that xconj - one for if the tree is nil (your first call), one if the val is less than the root (your second call). If neither match, the cond returns nil (your third call). Shouldn't there be a third case in the cond?


Aha! It only works if you supply the numbers in descending order, I had changed the numbers up from the example in the book. The case for a number that is bigger is missing, and further down the book it is included.

(defn xconj [t v]
    (nil? t) {:val v, :L nil, :R nil} 
    (< v (:val t)) {:val (:val t),
                :L (xconj (:L t) v),
                :R (:R t)}
    :else {:val (:val t),
           :L (:L t),
           :R (xconj (:R t) v)}))

Krishan V16:10:43

Any recommendations for a hacktoberfest friendly clojure project that are in need of PRs to fix bugs etc? Itching to get back into Clojure!