Last active
October 29, 2016 14:41
-
-
Save rauhs/e16eceb726308443a98eb682f77d4af9 to your computer and use it in GitHub Desktop.
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 take-while+ | |
"Identical to take-while but includes the false element." | |
[pred coll] | |
(lazy-seq | |
(when-let [[f & r] (seq coll)] | |
(if (pred f) | |
(cons f (take-while+ pred r)) | |
[f])))) | |
(defn partition-after | |
"Applies f to each value in coll, starting a new partition every time after f | |
returns a true value. Returns a lazy seq of partitions. Returns a stateful | |
transducer when no collection is provided." | |
([pred?] | |
(fn [rf] | |
(let [a (java.util.ArrayList.)] | |
(fn | |
([] (rf)) | |
([result] | |
(let [result (if (.isEmpty a) | |
result | |
(let [v (vec (.toArray a))] | |
(.clear a) | |
(unreduced (rf result v))))] | |
(rf result))) | |
([result input] | |
(.add a input) | |
(if (pred? input) | |
(let [v (vec (.toArray a))] | |
(.clear a) | |
(rf result v)) | |
result)))))) | |
([pred coll] | |
(lazy-seq | |
(when-let [s (seq coll)] | |
(let [fst (first s) | |
run (cons fst (take-while+ #(not (pred %)) (rest s)))] | |
(cons run (partition-after pred (drop (count run) s)))))))) | |
;; https://groups.google.com/d/msg/clojure/A4Xwlis_CT8/rBQz6BACfe0J | |
(defn partition-when | |
"Applies f to each value in coll, starting a new partition each time f | |
returns a true value. Returns a lazy seq of partitions. Returns a stateful | |
transducer when no collection is provided." | |
([f] | |
(fn [rf] | |
(let [a (java.util.ArrayList.)] | |
(fn | |
([] (rf)) | |
([result] | |
(let [result (if (.isEmpty a) | |
result | |
(let [v (vec (.toArray a))] | |
;;clear first! | |
(.clear a) | |
(unreduced (rf result v))))] | |
(rf result))) | |
([result input] | |
(if (.isEmpty a) | |
(do (.add a input) | |
result) | |
(if (f input) | |
(let [v (vec (.toArray a))] | |
(.clear a) | |
(let [ret (rf result v)] | |
(when-not (reduced? ret) | |
(.add a input)) | |
ret)) | |
(do | |
(.add a input) | |
result)))))))) | |
([f coll] | |
(lazy-seq | |
(when-let [s (seq coll)] | |
(let [fst (first s) | |
run (cons fst (take-while #(not (f %)) (next s)))] | |
(cons run (partition-when f (seq (drop (count run) s))))))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment