Created
April 13, 2015 11:38
-
-
Save arichiardi/27b319f8a744781d2955 to your computer and use it in GitHub Desktop.
Clojure partition w/ recur
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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