Reputation: 698
Can anyone explain me the stets of this clojure function
(defn to-list [{:keys [key left right] :as tree}]
(when tree
`(~@(to-list left) ~key ~@(to-list right))))
Upvotes: 1
Views: 79
Reputation: 1172
So the to-list
function expects a map that has some of three keys, namely key
, left
and right
. This map can be accessed also by the name tree
. See this for argument destructuring. Then you have a syntax quote (see this for details). It is roughly equivalent to
(clojure.core/seq (clojure.core/concat (to-list left)
(clojure.core/list key)
(to-list rirght)))
So basically if you have nil
for tree, it will return nil
(which seems reasonable). If you have a tree with a key left
(which is either nil or also a map possibly with keys key
, left
and right
), then left tree is recursively printed, then the key is added, then if you have a key right
, the right tree is printed recursively. If at any step you have only left or only right, the call (to-list left)
will yield nil and the rest will work as already explained.
I hope this helps.
NOTE I don't have a clojure repl right now, so I did not test what is the exact equivalent of syntax-quote, but it should be very something similar to the thing that I wrote.
Upvotes: 2