3

I am trying to become familiar with Clojure and so I've started to implement some basic algorithm and data structures. I currently have a problem with implementing a binary search tree. Here is my code:

(defstruct bst :left :right :key)

(defn add-bst [n bst-t]
  (cond
    (nil? bst-t) (struct-map bst :left nil :right nil :key n)
    (< n (:key bst-t))  (struct-map bst :left (add-bst n (:left bst-t))
                                :right (:right bst-t) :key (:key bst-t))
    (> n (:key bst-t))  (struct-map bst :left (:left bst-t)
                                :right (add-bst n (:right bst-t)) :key (:key bst-t))
    true bst-t))

I was trying to add random number into BST in the REPL, line so:

(exercise.new-ns/add-bst 5 nil)

But I get a NullPointerException, but I don't understand why I am getting this exception. Is there something wrong with my code?

1
  • If you are using at least Clojure 1.2, I would take a look at using deftype instead of defstruct. If you use deftype, you can also use protocols which will make add-bst and similar functions nicer because you can use extend-type on nil, effectively allowing your code to treat nil as if it were a BST node. Commented Feb 8, 2011 at 1:43

1 Answer 1

3

I suspect it is because you are re-using "bst" in your function parameters, which is confusing struct-map when the value is nil....

Try renaming the function parameter to something else.

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

3 Comments

I renamed the parameter and now I got the following error when trying to run this (add-bst 0 (struct-map bst :left nil :right nil :key 5)). Here is the error: #<CompilerException java.lang.IllegalArgumentException: No value supplied for key: 5
@haluk: in your struct-map calls you need to give the key as well as the value e.g. ":key (:key bst-t)" instead of just "(:key bst-t)"
all right, you are right, i fixed the code according to your tip.

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.