there is a separate fn in contrib and does exactly what you want
(assuming you don't care about the 2 passes):
(defn separate
"Returns a vector:
[ (filter f s), (filter (complement f) s) ]"
[f s]
[(filter f s) (filter (complement f) s)])
If you do care about the 2 passes you can always fall back to imperative
code + transients like so:
(defn separate [pred coll] ;;should be really fast as it only does a
single pass
(let [[yes no :as both] (list (transient []) (transient []))]
(doseq [x coll]
(if (pred x) (conj! yes x)
(conj! no x)))
(mapv persistent! both)))
Jim
On 04/04/13 13:16, Christian Romney wrote:
Hi all,
I was wondering if something in core (or new contrib) like this exists
already...
(defn segregate
"Takes a predicate, p, and a collection, coll, and separates the items
in coll
into matching and non-matching subsets. Like Scheme or Ruby's partition."
[p coll]
(loop [s coll y [] n []]
(if (empty? s) [y n]
(if (p (first s))
(recur (rest s) (conj y (first s)) n)
(recur (rest s) y (conj n (first s)))))))
(let [[odds evens] (segregate odd? (range 1 11))]
(println evens))
In Scheme (and Ruby) this function is partition, which is quite
different from /partition(-all|-by)?/ in Clojure:
#lang racket
(let-values [[(odds evens) (partition odd? (range 1 11))]]
(display evens))
If not, I have two follow-up questions.
1) Is there a better way to write segregate
2) Is this useful enough to consider adding to core?
TIA, and my apologies for the newbie question. :)
(Gist version if you prefer: https://gist.github.com/xmlblog/5309853)
--
--
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to [email protected]
Note that posts from new members are moderated - please be patient
with your first post.
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en
---
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To unsubscribe from this group and stop receiving emails from it, send
an email to [email protected].
For more options, visit https://groups.google.com/groups/opt_out.
--
--
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to [email protected]
Note that posts from new members are moderated - please be patient with your
first post.
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en
---
You received this message because you are subscribed to the Google Groups "Clojure" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
For more options, visit https://groups.google.com/groups/opt_out.