Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you make a binary search tree in Clojure?

Tags:

clojure

In Scheme, I can use define-struct to make a binary search tree, but how do you do it in Clojure?

like image 219
unj2 Avatar asked Oct 23 '09 02:10

unj2


2 Answers

You can use structmaps. To define one:

(defstruct bintree :left :right :key)

To make an instance:

(struct-map bintree :left nil :right nil :key 0)

You can then access the values in the struct like this:

(:left tree)

etc.

Or you can create new accessor functions:

(def left-branch (accessor bintree :left))

and use it:

(left-branch tree)
like image 189
Eric Normand Avatar answered Nov 14 '22 23:11

Eric Normand


I don't know Clojure, but I bet it's the same way you do it in Scheme without define-struct ... just cons together the left and right branches. To find something, recurse until you hit an atom.

Seriously, though, structmaps sound like what you want. I found this page. Look for structmaps about half way down.

like image 1
Nathan Shively-Sanders Avatar answered Nov 15 '22 01:11

Nathan Shively-Sanders