I was looking at Data.Set
, and I found out that it has no powerset
function. Why?
I can implement it like this:
import Data.Set (Set, empty, fromList, toList, insert)
powerset :: (Ord a) => Set a -> Set (Set a)
powerset s = fromList $ map (fromList) (powerList $ toList s)
powerList :: [a] -> [[a]]
powerList [] = [[]]
powerList (x:xs) = powerList xs ++ map (x:) (powerList xs)
But this doesn't seem the most efficient way of doing it. OK, I can also write
powerList :: [a] -> [[a]]
powerList = filterM (const [True, False])
but still, I wonder why Data.Set
has no powerset
function.
Also, what is the best way to write powerset :: (Ord a) => Set a -> Set (Set a)
?
Set
to be more efficient than a naive solution. But I don't think such a thing is very easy. And since Set is spine-strict, and since powerSet generates 2^n elements regardless, even if you make things as efficient as possible, you're not getting a whole bunch of mileage out of those optimizations... – BuckjumpOrd
instance onSet
is lexicographical order on the sorted list of elements. When constructing the power set, first remove the least elementx
and take the power set of the remainder, to gety
. Every element ofy
will be greater than every element ofmap (insert x) y
. – Venettavenezia