2
votes

In C++, there is a function in the standard library called stable_partition that takes a collection and a predicate. It divides the collection and puts those elements for which the predicate returns true in one place and those elements for which the predicate returns false in another place, while preserving the relative order of the elements.

I just wonder if there's something like this in a standard clojure library. I can't find such a function despite my searching. It might return a lazy sequence of two smaller collections, with one collection containing those elements for which the predicate returns true and the other collection containing those elements for which the predicate returns false.

It might look like this:

(stable-partition even? [1 2 3 4 5]) -> ([1 3 5] [2 4])

1

1 Answers

5
votes

The simplest version of this I think is:

(defn stable-partition [p? coll]
  (map (group-by p? coll) [false true]))

Since you say

"It divides the collection and puts those elements for which the predicate returns true in one place and those elements for which the predicate returns false in another place"

perhaps group-by itself is the answer (since vectors under keys in a hash-map are places after all).