Skip to content

Instantly share code, notes, and snippets.

@alvarogarcia7
Last active September 23, 2015 07:41
Show Gist options
  • Save alvarogarcia7/b88f34a847c4536f6f4d to your computer and use it in GitHub Desktop.
Save alvarogarcia7/b88f34a847c4536f6f4d to your computer and use it in GitHub Desktop.
Persisted tree kata
(defn mktree
([label l r] (cons label (cons l r)))
([leaf] (cons leaf (cons nil nil))))
(defn getlabel [t] (first t))
(defn getchildren [t] (rest t))
(defn getleft [t] (first (getchildren t)))
(defn getright [t] (rest (getchildren t)))
(defn find_ [t node]
(let [root (getlabel t)]
(cond
(nil? t) []
(== root node) node
(< root node) (find_ (getleft t) node)
(> root node) (find_ (getright t) node))))
(defn sum [tree]
(if (empty? tree) 0
(reduce +
[(first tree)
(sum (getleft tree))
(sum (getright tree))]
)))
(def t123
(mktree 1 (mktree 2) (mktree 3)))
(sum t123)
; 6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment