weavejester / medley

A lightweight library of useful Clojure functions
Eclipse Public License 1.0
870 stars 67 forks source link

split-when #47

Closed borkdude closed 1 year ago

borkdude commented 4 years ago

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))
yuhan0 commented 2 years ago

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))
borkdude commented 1 year ago

It seems this function is now available as partition-before