cartesian-product

clojure.contrib.combinatorics

  • (cartesian-product & seqs)
All the ways to take one item from each sequence

1 Example top

  • user> (use 'clojure.contrib.combinatorics)
    
    user> (cartesian-product ["A" "B"] ["a" "b"])
    (("A" "a") ("A" "b") ("B" "a") ("B" "b"))
    
    user> (cartesian-product ["A" "B"] ["a" "b"] [1 2])
    (("A" "a" 1) ("A" "a" 2) ("A" "b" 1) ("A" "b" 2) ("B" "a" 1) ("B" "a" 2) ("B" "b" 1) ("B" "b" 2))
Log in to add / edit an example.

See Also top

Log in to add a see also.

Plus_12x12 Minus_12x12 Source clojure/contrib/combinatorics.clj:107 top

(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? first seqs)
      (lazy-seq (step v-original-seqs)))))
Vars in clojure.contrib.combinatorics/cartesian-product: defn every? first lazy-seq let when
Used in 0 other vars

Comments top

No comments for cartesian-product. Log in to add a comment.