Skip to content

Instantly share code, notes, and snippets.

@ray1729
Created Dec 9, 2016
Embed
What would you like to do?
Split on pred implemented by reducing with a state machine
(defn split-after
[pred coll]
(let [post-accum (fn [accum x]
(update accum :after conj x))
pre-accum (fn [accum x]
(cond-> (update accum :before conj x)
(pred x) (assoc :f post-accum)))]
((juxt :before :after)
(reduce (fn [{:keys [f] :as accum} x] (f accum x))
{:before [] :after [] :f pre-accum}
coll))))
(defn split-before
[pred coll]
(let [post-accum (fn [accum x]
(update accum :after conj x))
pre-accum (fn [accum x]
(if (pred x)
(-> (update accum :after conj x)
(assoc :f post-accum))
(update accum :before conj x)))]
((juxt :before :after)
(reduce (fn [{:keys [f] :as accum} x] (f accum x))
{:before [] :after [] :f pre-accum}
coll))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment