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?
deftypeinstead ofdefstruct. If you usedeftype, you can also use protocols which will makeadd-bstand similar functions nicer because you can useextend-typeonnil, effectively allowing your code to treatnilas if it were a BST node.