The filter function is a commonly-used higher-order functions. It takes a function as an argument. The filter function works as its name implies. It filters out values in a sequence that don’t meet the given condition. To perform this filtering, filter takes a function and a sequence for its arguments. The function given to the filter must return a truthy value, and is called a predicate function. (see Truthiness)

The syntax is: (filter pred coll)

Let’s see the examples:

user=> ; when the values from 0 to 9 are not odd, those are filtered out
user=> (filter odd? (range 10))
(1 3 5 7 9)

We can use an anonymous function for filtering. The next example defines a flower list as a map (data structure) with simple keys and colors as values. From this map, the code below selects yellows or pinks.

user=> ; defines a flowers list as a map
user=> (def flowers
  #_=>   {:rose-a "red" :rose-b "yellow" :rose-c "pink"
  #_=>    :daisy-a "yellow" :daisy-b "white" :daisy-c "orange"
  #_=>    :tulip-a "pink" :tulip-b "orange" :tulip-c "yellow"})
#'user/flowers

user=> ; picks up yellows with the anonymous function #(= "yellow" (second %))
user=> (filter #(= "yellow" (second %)) flowers)
([:daisy-a "yellow"] [:rose-b "yellow"] [:tulip-c "yellow"])

user=> ; picks up pinks with the anonymous function #(= "pink" (second %))
user=> (filter #(= "pink" (second %)) flowers)
([:tulip-a "pink"] [:rose-c "pink"])

We can also use the function we defined for filtering. The third example selects palindromic numbers between 1000 and 4999. (see palindrome: http://en.wikipedia.org/wiki/Palindromic_number)

user=> ; defines the predicate function whether it is palindrome or not.
user=> (defn palindrome? [x]
  #_=>   (= (str x) (clojure.string/reverse (str x))))
#'user/palindrome?

user=> ; picks up numbers which are palindromes
user=> (filter palindrome? (range 1000 5000))
(1001 1111 1221 1331 1441 1551 1661 1771 1881 1991 2002 2112 2222 2332 2442 2552 2662 2772 2882 2992 3003 3113 3223 3333 3443 3553 3663 3773 3883 3993 4004 4114 4224 4334 4444 4554 4664 4774 4884 4994)


References