Skip to content

Instantly share code, notes, and snippets.

@ray1729
Created December 9, 2016 08:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ray1729/d834ef167c515cbc8fc6e2361cb692f9 to your computer and use it in GitHub Desktop.
Save ray1729/d834ef167c515cbc8fc6e2361cb692f9 to your computer and use it in GitHub Desktop.
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