medley
medley copied to clipboard
split-when
Hey @weavejester, I sometimes find myself in the need of this:
(defn split-when
[pred coll]
(lazy-seq
(when-let [s (seq coll)]
(let [fst (first s)
f (complement pred)
run (cons fst (take-while #(f %) (next s)))]
(cons run (split-when pred (lazy-seq (drop (count run) s))))))))
Could add a transducer arity-1 to it if this feels useful.
Example:
(split-when symbol? ['foo 1 2 3 'bar 5 6]) ;;=> ((foo 1 2 3) (bar 5 6))
Maybe a better name for this would be partition-when?
clojure.core naming conventions has split-* always returning a vector pair and partition-* returning a seq.
(split-when symbol? []) ;; => ()
(split-when symbol? [1 2 3]) ;; => ((1 2 3))
(split-when symbol? ['foo 1 2 3]) ;; => ((foo 1 2 3))
(split-when symbol? ['foo 1 2 3 'bar 5 6]) ;; => ((foo 1 2 3) (bar 5 6))
(split-when symbol? ['foo 1 2 3 'bar 5 6 'baz 'quux 7]) ;; => ((foo 1 2 3) (bar 5 6) (baz) (quux 7))
It would be nice to have a partition-upto too, in the case where you want
(partition-upto symbol? [1 2 'foo 3 'bar 4 5]) ;; => ((1 2 foo) (3 bar) (4 5))
It seems this function is now available as partition-before