Skip to content

Commit

Permalink
Merge pull request #68 from madstap/some-more-seq-fns
Browse files Browse the repository at this point in the history
Add repeatedly, tree-seq and flatten
  • Loading branch information
jeaye committed May 4, 2024
2 parents 9459f95 + 33c7066 commit 12b27e2
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions src/jank/clojure/core.jank
Original file line number Diff line number Diff line change
Expand Up @@ -2030,6 +2030,13 @@
(when-let [s (seq coll)]
(cons (first s) (take (dec n) (rest s))))))))

(defn repeatedly
"Takes a function of no args, presumably with side effects, and
returns an infinite (or length n if supplied) lazy sequence of calls
to it"
([f] (lazy-seq (cons (f) (repeatedly f))))
([n f] (take n (repeatedly f))))

; Returns a lazy sequence of successive items from coll while
; (pred item) returns logical true. pred must be free of side-effects.
; Returns a transducer when no collection is provided.
Expand Down Expand Up @@ -2563,6 +2570,21 @@
([f coll]
(apply concat (map f coll))))

(defn tree-seq
"Returns a lazy sequence of the nodes in a tree, via a depth-first walk.
branch? must be a fn of one arg that returns true if passed a node
that can have children (but may not). children must be a fn of one
arg that returns a sequence of the children. Will only be called on
nodes for which branch? returns true. Root is the root node of the
tree."
[branch? children root]
(let [walk (fn walk [node]
(lazy-seq
(cons node
(when (branch? node)
(mapcat walk (children node))))))]
(walk root)))

; Returns a lazy sequence of the items in coll for which
; (pred item) returns logical true. pred must be free of side-effects.
; Returns a transducer when no collection is provided.
Expand Down Expand Up @@ -2593,6 +2615,14 @@
(cons f (filter pred r))
(filter pred r))))))))

(defn flatten
"Takes any nested combination of sequential things (lists, vectors,
etc.) and returns their contents as a single, flat lazy sequence.
(flatten nil) returns an empty sequence."
[x]
(filter (complement sequential?)
(rest (tree-seq sequential? seq x))))

; Returns a lazy sequence of the items in coll for which
; (pred item) returns logical false. pred must be free of side-effects.
; Returns a transducer when no collection is provided.
Expand Down

0 comments on commit 12b27e2

Please sign in to comment.