Skip to content

Commit 5fd95de

Browse files
committed
Merge pull request #197 from kgann/tree-seq
implement pixie.stdlib/tree-seq
2 parents 0b1f7e1 + 358cb86 commit 5fd95de

File tree

2 files changed

+22
-1
lines changed

2 files changed

+22
-1
lines changed

pixie/stdlib.pxi

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2126,3 +2126,16 @@ Expands to calls to `extend-type`."
21262126
:added "0.1"}
21272127
([] (trace *e))
21282128
([e] (seq e)))
2129+
2130+
(defn tree-seq
2131+
"Returns a lazy sequence of the nodes in a tree via a depth-first walk.
2132+
branch? - fn of node that should true when node has children
2133+
children - fn of node that should return a sequence of children (called if branch? true)
2134+
root - root node of the tree"
2135+
[branch? children root]
2136+
(let [walk (fn walk [node]
2137+
(lazy-seq
2138+
(cons node
2139+
(when (branch? node)
2140+
(mapcat walk (children node))))))]
2141+
(walk root)))

tests/pixie/tests/test-stdlib.pxi

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -378,10 +378,18 @@
378378
(t/assert= (transduce (drop-while even?) conj [0 2] [1 4 6]) [0 2 1 4 6])
379379
(t/assert= (transduce (drop-while even?) conj [0 2] [2 4 6 7 8]) [0 2 7 8]))
380380

381-
382381
(t/deftest test-trace
383382
(try
384383
(/ 0 0)
385384
(catch e
386385
(t/assert= (first (trace e)) {:type :runtime :data "Divide by zero"})
387386
(t/assert= (second (trace e)) {:type :native :name "_div"} ))))
387+
388+
(t/deftest test-tree-seq
389+
(t/assert= (vec (filter string?
390+
(tree-seq map?
391+
:ch
392+
{:ch [{:ch ["a" "b"]}
393+
{:ch ["c" "d"]}
394+
{:ch [{:ch ["e" {:ch ["f"]}]}]}]})))
395+
["a" "b" "c" "d" "e" "f"]))

0 commit comments

Comments
 (0)