Skip to content

Instantly share code, notes, and snippets.

@agarman
Created April 13, 2014 01:56
Show Gist options
  • Save agarman/10565555 to your computer and use it in GitHub Desktop.
Save agarman/10565555 to your computer and use it in GitHub Desktop.
Helpful combinatoric functions for Clojure
(defn powerset [[h & t]]
(if (nil? h)
[()]
(for [x (powerset t)
y [x (cons h x)]]
y)))
(defn tails [[ _ & t :as xs]]
(when xs (cons xs (tails t))))
(defn k-combinations [k l]
(if (zero? k)
[[]]
(for [[x & xs] (tails (seq l))
ys (k-combinations (dec k) xs)]
(cons x ys))))
(defn combinations [& [hs & tss]]
(if (empty? hs)
[[]]
(for [h hs
ts (apply combinations tss)]
(cons h ts))))
(defn distribute [e [h & t :as xs]]
(if (empty? xs)
[[e]]
(cons (cons e xs)
(map #(cons h %) (distribute e t)))))
(defn permutations [xs]
(if-let [[e & t] xs]
(mapcat #(distribute e %) (permutations t))
[[]]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment