1.3.0 permalink Arrow_down_16x16

partition

clojure.core

  • (partition n coll)
  • (partition n step coll)
  • (partition n step pad coll)
Returns a lazy sequence of lists of n items each, at offsets step
apart. If step is not supplied, defaults to n, i.e. the partitions
do not overlap. If a pad collection is supplied, use its elements as
necessary to complete last partition upto n items. In case there are
not enough padding elements, return a partition with less than n items.

3 Examples top

  • user=> (partition 4 (range 20))
    ((0 1 2 3) (4 5 6 7) (8 9 10 11) (12 13 14 15) (16 17 18 19))
    
    user=> (partition 4 (range 22))
    ((0 1 2 3) (4 5 6 7) (8 9 10 11) (12 13 14 15) (16 17 18 19))
    
    user=> (partition 4 6 (range 20))
    ((0 1 2 3) (6 7 8 9) (12 13 14 15))
    
    user=> (partition 4 6 ["a"] (range 20))
    ((0 1 2 3) (6 7 8 9) (12 13 14 15) (18 19 "a"))
    
    user=> (partition 4 6 ["a" "b" "c" "d"] (range 20))
    ((0 1 2 3) (6 7 8 9) (12 13 14 15) (18 19 "a" "b"))
    
  • user=> (partition 3 1 [:a :b :c :d :e :f])
    ((:a :b :c) (:b :c :d) (:c :d :e) (:d :e :f))
    
  • ;; When there are less than n items in the coll, partition's behaviour
    ;; depends on whether there is a pad or not
    
    ;; without pad
    user> (partition 10 [1 2 3 4])
    ()
    ;; again, without pad
    user> (partition 10 10 [1 2 3 4])
    ()
    ;; with a pad this time (note: the pad is an empty sequence)
    user> (partition 10 10 nil [1 2 3 4])
    ((1 2 3 4))
    ;; or, explicit empty sequence instead of nil
    user> (partition 10 10 [] [1 2 3 4])
    ((1 2 3 4))
    
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:2765 top

(defn partition
  "Returns a lazy sequence of lists of n items each, at offsets step
  apart. If step is not supplied, defaults to n, i.e. the partitions
  do not overlap. If a pad collection is supplied, use its elements as
  necessary to complete last partition upto n items. In case there are
  not enough padding elements, return a partition with less than n items."
  {:added "1.0"
   :static true}
  ([n coll]
     (partition n n coll))
  ([n step coll]
     (lazy-seq
       (when-let [s (seq coll)]
         (let [p (doall (take n s))]
           (when (= n (count p))
             (cons p (partition n step (nthrest s step))))))))
  ([n step pad coll]
     (lazy-seq
       (when-let [s (seq coll)]
         (let [p (doall (take n s))]
           (if (= n (count p))
             (cons p (partition n step pad (nthrest s step)))
             (list (take n (concat p pad)))))))))
Vars in clojure.core/partition:
Used in 0 other vars

Comments top

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