Last active
September 23, 2015 07:41
-
-
Save alvarogarcia7/b88f34a847c4536f6f4d to your computer and use it in GitHub Desktop.
Persisted tree kata
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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