September 11, 2018

Just Juxt #28: Power Set (4clojure #85)

Power Set

Write a function which generates the power set of a given set. The power set of a set x is the set of all subsets of x, including the empty set and x itself.

(ns live.test
  (:require [cljs.test :refer-macros [deftest is testing run-tests]]))
  
(defn powerset [s]
    (if (empty? s)
      #{s}
      (let [[h t] ((juxt first (comp powerset set next)) s)]
        (set (concat t (map #(conj % h) t))))))

(deftest powerset-test
  (is (= (powerset #{1 :a}) #{#{1 :a} #{:a} #{} #{1}}))
  (is (= (powerset #{}) #{#{}}))
  (is (= (powerset #{1 2 3}) #{#{} #{1} #{2} #{3} #{1 2} #{1 3} #{2 3} #{1 2 3}}))
  (is (= (count (powerset (into #{} (range 10)))) 1024)))
  
(run-tests)
Tags: coding exercises KLIPSE 4clojure Cryogen juxt