I need to split/partition some lists based on wether they match a regex. I need only two lists back, [matching, not-matching]. This springs to mind:
(defn- bisect-all-by [pred coll]
(let [matching (filter pred coll)
not-matching (remove pred coll)]
[matching not-matching]))
(defn- partition-all-by [pred coll]
(->> coll (group-by pred) vals))
(comment
(bisect-all-by #(< (count %) 6) ["apple" "banana" "cherry" "date" "elderberry" "date"])
;; => [("apple" "date" "date") ("banana" "cherry" "elderberry")]
(bisect-all-by #(re-find #"[an]" %) ["apple" "banana" "cherry" "date" "elderberry" "date"])
;; => [("apple" "banana" "date" "date") ("cherry" "elderberry")]
(bisect-all-by identity ["apple" "banana" "cherry" "date" "elderberry" "date"])
;; => [("apple" "banana" "cherry" "date" "elderberry" "date") ()]
(partition-all-by #(< (count %) 6) ["apple" "banana" "cherry" "date" "elderberry" "date"])
;; => (["apple" "date" "date"] ["banana" "cherry" "elderberry"])
(partition-all-by #(re-find #"[an]" %) ["apple" "banana" "cherry" "date" "elderberry" "date"])
;; => (["apple" "banana" "date" "date"] ["cherry" "elderberry"])
(partition-all-by identity ["apple" "banana" "cherry" "date" "elderberry" "date"])
;; => (["apple"] ["banana"] ["cherry"] ["date" "date"] ["elderberry"])
:rcf)
Both work fine for my use case. And I donโt much need any lazyness. But Iโm curious about what you other peeps think are the trade-offs/problems with these and what alternatives you would consider.If you're only ever supplying predicates (which return true or false) then group-by will return an ordered array-map (because the number of groups is small). But yeah, it's relying on an implementation detail. Being explicit is probably better:
(defn true+false-groups [pred coll]
(let [{t true f false} (group-by pred coll)]
[t f]))
And using the word partition in the name may be confusing to clojurians because in core that means keeping everything in the original order, despite the partitions being there. Whereas group-by based approaches don'tThanks! The unordered thing would bite me hard if the implementation change. ๐