medley icon indicating copy to clipboard operation
medley copied to clipboard

split-when

Open borkdude opened this issue 5 years ago • 1 comments

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))

borkdude avatar May 03 '20 14:05 borkdude

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))

yuhan0 avatar May 04 '22 23:05 yuhan0

It seems this function is now available as partition-before

borkdude avatar Jan 27 '23 12:01 borkdude