ClojureDocs

导航

命名空间

take-while

clojure.core

自 1.0 起可用 (源代码)
  • (take-while pred)
  • (take-while pred coll)
Returns a lazy sequence of successive items from coll while
(pred item) returns logical true. pred must be free of side-effects.
Returns a transducer when no collection is provided.
5 Examples
;; Calculate the sum of all numbers under 1000:
user=> (reduce + (take-while (partial > 1000) (iterate inc 0)))
499500
user=> (take-while neg? [-2 -1 0 1 2 3])
(-2 -1)

user=> (take-while neg? [-2 -1 0 -1 -2 3]) ; note: `take-while' stops traversing the collection when the predicate is false, as is different from `filter'.
(-2 -1)

user=> (take-while neg? [ 0 1 2 3])
()

user=> (take-while neg? [])
()

user=> (take-while neg? nil)
()
;;take the item while it's included in the set  
user=> (take-while #{[1 2][3 4]} #{[1 2]})
([1 2])
user=> (take-while #{[1 2][3 4]} #{[3 4]})
([3 4])
user=> (take-while #{[1 2][3 4]} #{[4 5]})
()
user=>(take-while #{[1 2][3 4]} #{[5 6] [1 2]}); return nil while any item is not included in the set
()
;;take-while practical example

(def entries [{:month 1 :val 12}
              {:month 2 :val 3}
              {:month 3 :val 32}
              {:month 4 :val 18}
              {:month 5 :val 32}
              {:month 6 :val 62}
              {:month 7 :val 12}
              {:month 8 :val 142}
              {:month 9 :val 52}
              {:month 10 :val 18}
              {:month 11 :val 23}
              {:month 12 :val 56}])

(defn get-result
  [coll m]
  (take-while
   #(<= (:month %) m) coll))

(get-result entries 3)
;;({:m 1, :val 12} {:m 2, :val 3} {:m 3, :val 32})
;; Note that usually more items are realized than needed.
;; In the example below the first 32 items are calculated,
;; though the first 2 would be enough.
;; This can be especially important when this extra realization
;; leads to an exception (see example at 'take') or requires a lot of
;; resources (CPU, time, memory, etc.) and at the end not needed at all.

user=> (let [x (map (fn [i]
                      (println i)
                      (Thread/sleep 100)
                      i)
                    (range 50))]
         (take-while #(< % 1) x))
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
(0)
See Also

Returns a lazy sequence of the items in coll starting from the first item for which (pred item) re...

Added by pauldoo

Returns a vector of [(take-while pred coll) (drop-while pred coll)]

Added by dansalmo

Returns the first logical true value of (pred x) for any x in coll, else nil. One common idiom is...

Added by huahaiy

Returns a lazy sequence of the first n items in coll, or all items if there are fewer than n. Ret...

Added by cljlc
0 Notes
No notes for take-while