Skip to content

Instantly share code, notes, and snippets.

@ichramm
Created June 4, 2020 13:54
Show Gist options
  • Save ichramm/05a9b267e8a5cd0be2b1450b469cb079 to your computer and use it in GitHub Desktop.
Save ichramm/05a9b267e8a5cd0be2b1450b469cb079 to your computer and use it in GitHub Desktop.
Removes all elements matching a predicate, except the last one
(defn remove-all-but-last
[pred coll]
(let [[_ count index] (reduce #(if (pred %2)
[(inc (% 0)) (inc (% 1)) (% 0)]
[(inc (% 0)) (% 1) (% 2)])
[0 0 nil]
coll)]
(if (> count 1)
(keep-indexed #(and (or (not (pred %2)) (= index %1) nil) %2) coll)
coll)))
@ichramm
Copy link
Author

ichramm commented Oct 22, 2020

(defn butlast-pred
  [pred coll]
  (let [tgts (filter pred coll)]
    (remove #(and (pred %) (not= % (last tgts)) ) coll)))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment