Reputation:
What is the best way to remove the nils in a 2D-Vector in Clojure?
[[250 634]] [[450 598] [250 651]] [[450 615] [250 668]] [[450 632] [250 685]] [[450 649] [259 700]] [[450 666] [323 700]] [[450 683] [386 700]] [nil nil] [nil nil] [nil nil] [nil nil] [nil nil] [nil nil] [nil nil]]
Upvotes: 0
Views: 408
Reputation: 13473
mapv
is a variant of map
that returns a vector. In the same way, can define removev
: a variant of remove
that returns a vector:
(defn removev [pred v]
(into [] (remove pred v)))
We can make a predicate that detects [nil nil]
by wrapping it in a set: #{[nil nil]}
.
By combining these, we have what we want:
(removev #{[nil nil]} [[1 3] [nil nil] [2 nil]])
=> [[1 3] [2 nil]]
I've just noticed that this answer is essentially the same as Denis Fuenzola's, except that this one converts the answer back to a vector.
Upvotes: 0
Reputation: 3346
You can use remove
to remove elements out of a collection if they meet the criteria of a given predicate function. Now, you can use a set
as a function, so you can use the set #{[nil nil]}
to remove the undesired elements, like this:
user=> (def elems [[[250 634]] [[450 598] [250 651]] [[450 615] [250 668]] [[450 632] [250 685]] [[450 649] [259 700]] [[450 666] [323 700]] [[450 683] [386 700]] [nil nil] [nil nil] [nil nil] [nil nil] [nil nil] [nil nil] [nil nil]])
#'user/elems
user=> (remove #{[nil nil]} elems)
([[250 634]] [[450 598] [250 651]] [[450 615] [250 668]] [[450 632] [250 685]] [[450 649] [259 700]] [[450 666] [323 700]] [[450 683] [386 700]])
Upvotes: 2
Reputation: 21926
(filter (fn [x] (every? not-nil x) your-vec)
Filters the vector by making sure that the sub-vector isn't just full of nils. If you want to filter out any vectors with nil use some instead of every?. If you want to keep the (potentially empty) sub-vectors then use filter instead of every?:
(filter (fn [x] (filter not-nil x) your-vec)
Upvotes: 0