Remove-by fn

Very generic, but I didn’t see it in core. I thought I’d share here; I like the using partial where it’s elegant, and I’m practicing rich comments. I’m open to suggestions or if there’s a core fn I missed.

(defn val=
  [val kw source]
  (= val (kw source)))

(defn remove-by
  "Remove from a seq-of-maps `s`"
  [s by-fn val]
  (remove (partial val= val by-fn) s))

(comment
  (let [s [{:id 1} {:id 3}]]
    (remove-by s :id 3))
  ;; ({:id 1})
  )

I am not aware of anything in Clojure core library that matches what you have exactly. It isn’t the goal of the Clojure core library to have everything one might think is useful – more that it is a pretty big fairly general toolbox from which many other things can be built without a lot of work, like your remove-by.

One small comment on generality and naming – The argument you call kw to val= is only ever a keyword in the way you test it, and perhaps in the way you plan to use it, but note that it can in general be any function that takes 1 argument, so perhaps naming it something like f or by-fn instead of kw would help signal that generality.

user> (def s [{:id 1} {:id 3}])
#'user/s
user> (remove (comp #{3} :id) s)
({:id 1})
3 Likes

comp with a set – nice!

On your first paragraph, agreed; one of the benefits of Clojure is the effective leanness of its core. On the other hand, I’ve been caught by things I didn’t know were in core previously.

You naming critique was correct; I was writing quickly. I think I read “key” in core functions (like assoc) and wrote it as kw here.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.