Contents    Page-10    Prev    Next    Page+10    Index   

Filter a List

A filter keeps items in a list that pass some test, while removing other items.


(defn myfilter [fn lst]
  (if (empty? lst)       ;  base case
      '()
      (if (fn (first lst))   ; does it pass?
          (cons (first lst)  ; yes: keep it
                (myfilter fn (rest lst)))
          ; else: ignore it but keep going
          (myfilter fn (rest lst)) ) ) )

user=> (myfilter number? '(2 a d 4 3 d e 8))

(2 4 3 8)

filter is a built-in function of Clojure.