1.3.0 permalink Arrow_down_16x16
  • (keep f coll)
Returns a lazy sequence of the non-nil results of (f item). Note,
this means false return values will be included. f must be free of
side-effects.

3 Examples top

  • user=> (keep even? (range 1 10))
    (false true false true false true false true false)
    
  • ;; comparisons among keep, map and for.
    
    user> (keep #(if (odd? %) %) (range 10))
    (1 3 5 7 9)
    user> (map #(if (odd? %) %) (range 10))
    (nil 1 nil 3 nil 5 nil 7 nil 9)
    user> (for [ x (range 10) :when (odd? x)] x)
    (1 3 5 7 9)
    
    user> (keep #(if(even? %) %) (range 10))
    (0 2 4 6 8)
    user> (map #(if (even? %) %) (range 10))
    (0 nil 2 nil 4 nil 6 nil 8 nil)
    user> (for [ x (range 10) :when (even? x)] x)
    (0 2 4 6 8)
    
    
  • ;; Sieve of Eratosthenes by using 'keep'.
    
    (defn keep-mcdr [f coll]
      (lazy-seq
         (when-let [x (first coll)]
           (cons x  (keep-mcdr f (f x (rest coll)))))))
    
    (defn prime-number [n]
      (cons 1
    	(keep-mcdr
    	 (fn[x xs] (if (not-empty xs)
    		     (keep #(if-not (zero? (rem % x)) %)
    			   xs)))
    	 (range 2 n))))
    
    user> (prime-number 100)
    (1 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97)
    
Log in to add / edit an example.

See Also top

Log in to add a see also.

Plus_12x12 Minus_12x12 Source clojure/core.clj:6333 top

(defn keep
  "Returns a lazy sequence of the non-nil results of (f item). Note,
  this means false return values will be included.  f must be free of
  side-effects."
  {:added "1.2"
   :static true}
  ([f coll]
   (lazy-seq
    (when-let [s (seq coll)]
      (if (chunked-seq? s)
        (let [c (chunk-first s)
              size (count c)
              b (chunk-buffer size)]
          (dotimes [i size]
            (let [x (f (.nth c i))]
              (when-not (nil? x)
                (chunk-append b x))))
          (chunk-cons (chunk b) (keep f (chunk-rest s))))
        (let [x (f (first s))]
          (if (nil? x)
            (keep f (rest s))
            (cons x (keep f (rest s))))))))))
Vars in clojure.core/keep:
Used in 0 other vars

Comments top

No comments for keep. Log in to add a comment.