You're viewing version 1.2.0 of partition. The latest stable version of Clojure Core is 1.3.0.
1.2.0 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:2354 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"}
  ([n coll]
     (partition n n coll))
  ([n step coll]
     (lazy-seq
       (when-let [s (seq coll)]
         (let [p (take n s)]
           (when (= n (count p))
             (cons p (partition n step (drop step s))))))))
  ([n step pad coll]
     (lazy-seq
       (when-let [s (seq coll)]
         (let [p (take n s)]
           (if (= n (count p))
             (cons p (partition n step pad (drop step s)))
             (list (take n (concat p pad)))))))))
Vars in clojure.core/partition: = concat cons count defn drop lazy-seq let list take when when-let

Comments top

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