Created

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist
View partition.clj
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 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
;; A lot of times I needed a padding option on the partition. This is
;; my attempt to solve this problem. Any suggestions are welcome. I
;; hope this patch or something simmilar will make its way into the
;; core.
 
(ns my
(:refer-clojure :exclude [partition])
(:use [clojure.contrib.test-is :only [deftest is are run-tests]]))
(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 pad is supplied, pad as necessary to complete
last partition upto n items. In case there is not enough padding
elements, return a partition with less than n items."
([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)))))))))
(deftest test-partition-with-pad
(are (= _1 _2)
(partition 3 3 "pad" "coll") [[\c \o \l] [\l \p \a]]
(partition -3 3 "pad" "coll") [[]]
(partition 3 3 nil [1 2 3 4 5]) [[1 2 3] [4 5]]
(partition 3 3 [] [1 2 3 4 5]) [[1 2 3] [4 5]]
(partition 3 3 [:a :b :c] [1 2 3 4 5]) [[1 2 3] [4 5 :a]]
(partition 3 3 [:a :b :c] [1 2 3 4 5 6]) [[1 2 3] [4 5 6]]
(partition 4 5 [:a :b] [1 2 3 4 5 6]) [[1 2 3 4] [6 :a :b]]
(partition 6 2 [:a :b] [1 2 3 4 5 6]) [[1 2 3 4 5 6] [3 4 5 6 :a :b]]
(partition 3 3 (repeat nil) [1 2 3 4]) [[1 2 3] [4 nil nil]]
(partition 4 5 (cycle [:a :b]) [1 2 3 4 5 6]) [[1 2 3 4] [6 :a :b :a]]
(for [[a b c] (partition 3 3 (repeat 0) [1 2 3 4])] [a b c]) [[1 2 3] [4 0 0]]
(map second (partition 2 3 (repeat 0) [1 2 3 4])) [2 0]))
(deftest test-partition
(are (= _1 _2)
(partition 2 [1 2 3]) '((1 2))
(partition 2 [1 2 3 4]) '((1 2) (3 4))
(partition 2 []) ()
(partition 2 3 [1 2 3 4 5 6 7]) '((1 2) (4 5))
(partition 2 3 [1 2 3 4 5 6 7 8]) '((1 2) (4 5) (7 8))
(partition 2 3 []) ()
(partition 1 []) ()
(partition 1 [1 2 3]) '((1) (2) (3))
(partition 5 [1 2 3]) ()
; (partition 0 [1 2 3]) (repeat nil) ; infinite sequence of nil
(partition -1 [1 2 3]) ()
(partition -2 [1 2 3]) () ))
(run-tests)
(comment
(time (count (partition 13 (range 10000000))))
(time (count (partition 13 7 (range 10000000))))
(time (count (partition 13 7 (range 10000000) (repeat 0)))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.