Skip to content

Instantly share code, notes, and snippets.

@ray1729
Created June 21, 2013 11:27
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 ray1729/5830608 to your computer and use it in GitHub Desktop.
Save ray1729/5830608 to your computer and use it in GitHub Desktop.
Using Clojure to compute partitions of a set
(defn expand-partition
"Given a partition of size n and an element, generate n new
partitions by adding `element` to each subset in turn."
[partition element]
(let [partition (vec partition)]
(for [i (range (count partition))]
(set (update-in partition [i] #(conj % element))))))
(defn partitions
"Return all partitions of the set `X` into `n` non-empty subsets.
When `n` is not specified, return all partitions of `X`"
([X n]
(cond
(< n 1) '()
(> n (count X)) '()
(= n 1) (list #{X})
(= n (count X)) (list (set (map hash-set X)))
:else (let [x (first X)
xs (disj X x)]
(lazy-cat (map (fn [p] (conj p #{x})) (partitions xs (dec n)))
(mapcat (fn [p] (expand-partition p x)) (partitions xs n))))))
([X]
(mapcat (partial partitions X) (range 1 (inc (count X))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment