4 ms·
Another two functions that I forgot to mention last night are filter and keep. I am actually surprise filter isn't already on the site. filter takes a predicat
by jetti 5y ago
Another two functions that I forgot to mention last night are filter and keep. I am actually surprise filter isn't already on the site.
filter takes a predicate and a collection and will return a lazy sequence of all items that the predicate returns logically true. For example:
(filter odd? [1 2 3 4])
would return a lazy sequence of (1 3)
keep is a function that I was unaware of (and most of my team was too) until I was turned on to it by a former coworker. keep takes a function and a collection and returns a lazy sequence of non-nil results. For instance, if I have a collection of maps and I want to only get a value of a specific key I could do the following with map and remove
(def items [{:v "hi"} {:v "there"} {:m "not v"}])
(remove nil? (map :v items))
What the map does is get the key `v` from each map in the collection and we end up with a sequence that looks like `("hi" "there" nil)` Since the last map in the collection `items` does not have a key `v` the value will return nil. We would then need to use the remove function with the nil? predicate which will remove all items in the collection that are nil. If we use keep, though, we could do this in one pass.
(def items [{:v "hi"} {:v "there"} {:m "not v"}])
(keep :v items)
Because keep already removes nil for us we end up with `("hi" "there")`