Created
July 19, 2013 12:15
-
-
Save svdmitrij/9588fb41352ebcf76ee3 to your computer and use it in GitHub Desktop.
Cartesian product
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 cartesian-product | |
"All the ways to take one item from each sequence" | |
[& seqs] | |
(let [v-original-seqs (vec seqs) | |
step | |
(fn step [v-seqs] | |
(let [increment | |
(fn [v-seqs] | |
(loop [i (dec (count v-seqs)), v-seqs v-seqs] | |
(if (= i -1) nil | |
(if-let [rst (next (v-seqs i))] | |
(assoc v-seqs i rst) | |
(recur (dec i) (assoc v-seqs i (v-original-seqs i)))))))] | |
(when v-seqs | |
(cons (map first v-seqs) | |
(lazy-seq (step (increment v-seqs)))))))] | |
(when (every? seq seqs) | |
(lazy-seq (step v-original-seqs))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment