I think I have correctly implemented Powerset in Clojure.
(use '(clojure set))
(defn powerset [input result]
(if (nil? (first input))
(concat result #{})
(set (reduce concat
(for [x input]
(let [set-of-x #{x}
input-no-x (set (remove set-of-x input))
next-result (union result (set (list input set-of-x input-no-x)))]
(powerset input-no-x next-result)))))))
Of course I'm interested in how a library function could make the above a one-liner, but I'm also interested in how the above code could be made more idiomatic.
(if (nil? (first input))
feels wrong.- Using the
let
block to replicate imperative calculations. Acceptable? - Could I use
->>
to make the following line more readable?(union result (set (list input set-of-x input-no-x)))
- I'm not using
recur
as I got the "recur must be in the tail position" compiler error.
EDIT Removed (loop)
from originally-posted version. - I had erroneously copy-pasted code after I had already commenced attempting to introduce loop/recur (tail recursion). How use loop/recur in this function?
math.combinatorics/subsets
\$\endgroup\$