Skip to content

Instantly share code, notes, and snippets.

@stathissideris
Last active September 13, 2015 04:50
Show Gist options
  • Save stathissideris/9500581 to your computer and use it in GitHub Desktop.
Save stathissideris/9500581 to your computer and use it in GitHub Desktop.
Reduce with multiple accumulators
(reduce
(fn [{:keys [odd even]} datum]
(if (odd? datum)
{:odd (conj odd datum)
:even even}
{:odd odd
:even (conj even datum)}))
{:odd []
:even []}
(range 20))
;;{:odd [1 3 5 7 9 11 13 15 17 19], :even [0 2 4 6 8 10 12 14 16 18]}
(defn sieve [pred coll]
(reduce
(fn [[acc rej] x]
(if (pred x)
[(conj acc x) rej]
[acc (conj rej x)]))
[[] []] coll))
;;user> (sieve odd? (range 20))
;; [[1 3 5 7 9 11 13 15 17 19] [0 2 4 6 8 10 12 14 16 18]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment