split-with

added
1.0

ns
clojure.core

type
function

(split-with pred coll)

Returns a vector of [(take-while pred coll) (drop-while pred coll)]

                user=> (split-with (partial >= 3) [1 2 3 4 5])
[(1 2 3) (4 5)]

user=> (split-with (partial > 3) [1 2 3 2 1])
[(1 2) (3 2 1)]

user=> (split-with (partial > 10) [1 2 3 2 1])
[(1 2 3 2 1) ()]
            
                ;; If your plan is to split based on a certain value, using sets as
;; predicates here isn't entirely straightforward.

user=> (split-with #{:c} [:a :b :c :d])
[() (:a :b :c :d)]

;; This is because the split happens at the first false/nil predicate result.
;; Your predicate should thus return false upon hitting the desired split value!

user=> (split-with (complement #{:c}) [:a :b :c :d])
[(:a :b) (:c :d)]

;; In short, the predicate defines an attribute valid for the whole left
;; side of the split. There's no such guarantee for the right side!

user=> (split-with odd? [1 3 5 6 7 9])
[(1 3 5) (6 7 9)]

;; Except if your predicate never returns false.
user=> (split-with (complement #{:e}) [:a :b :c :d])
[(:a :b :c :d) ()]