Skip to content

Instantly share code, notes, and snippets.

@arichiardi
Created April 13, 2015 11:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arichiardi/27b319f8a744781d2955 to your computer and use it in GitHub Desktop.
Save arichiardi/27b319f8a744781d2955 to your computer and use it in GitHub Desktop.
Clojure partition w/ recur
(defn- part-iter
([n step step-coll part-coll i part parts]
(if (seq step-coll)
(if (and (seq part-coll) (< i n))
(recur n step step-coll (rest part-coll) (inc i) (cons (first part-coll) part) parts)
(let [nthrst (drop (int step) step-coll)]
(recur n step nthrst nthrst 0 nil (cons (reverse part) parts))))
(reverse (if (seq part)
(cons (reverse part) parts)
parts))))
;; ([n coll i part parts]
;; (if (seq coll)
;; (if (< i n)
;; (recur n (rest coll) (inc i) (cons (first coll) part) parts)
;; (recur n coll 0 () (cons (reverse part) parts)))
;; (reverse (if (seq part)
;; (cons (reverse part) parts)
;; parts))))
)
;; (deftest test-partition
;; (are [x y] (= x y)
;; (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]) ()
;; (partition 0 nil) ()
;; (partition 2 nil) ()
;; (partition 0 []) ()
;; (partition 2 []) ()
;; ))
(defn- partition
([n coll] (lazy-seq (part-iter n n coll coll 0 () ())))
([n step coll] (lazy-seq (part-iter n step coll coll 0 () ()))
;; ([n step pad coll]
;; (lazy-seq (partition n coll 0 () ())))
))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment