Fork me on GitHub
#beginners
<
2016-06-03
>
gamecubate16:06:13

Hello everyone. How would you filter a vector, removing those elements that did not satisfy specific predicates? Example: given vector v,

(def v [:odd :even :1 :2 :3])
, I need to define function f such that:
(f v 1) -> [:odd :1]
,
(f v 2) -> [:even :2]
,
(f v 99) -> [:odd]
,
(f v 0) -> [:even]
, etc.

seancorfield16:06:18

So you have some function that transforms the elements in the vector into actual predicates, I assume?

gamecubate16:06:08

I was thinking of, for each keyword in v, defining a matches-item predicate function indeed.

seancorfield16:06:26

Let’s call that ->pred, then f would be (defn f [pred-vec value] (filterv #((->pred %) value) pred-vec))

gamecubate16:06:36

<digesting this>

gamecubate16:06:21

Are you thinking of something like this?

(defn ->pred [kw] (case kw :odd odd? :even even? :1 #(= 1 %) ...

gamecubate16:06:01

Wow. It actually works. Thanks a lot for this!

seancorfield17:06:42

I was thinking of ->pred just being a hash map but, yeah.

gamecubate20:06:03

Other question: given a map, what is the simplest way to reset all its values to, say, 0?

gamecubate20:06:25

(defn cleared [m] (into {} (for ([k v] m] (assoc k 0))))

gamecubate21:06:57

(defn cleared [m] (zipmap (keys m) (repeat 0)))
seems to work.

plexus21:06:18

oh yeah that's nice and clean

gamecubate21:06:23

so simple seems sinful. 🙂