From c34ccfdfb5a18d35cd2a9d039b7e71dacc142b21 Mon Sep 17 00:00:00 2001 From: Matthew Leon Date: Mon, 15 Jan 2018 17:17:43 -0500 Subject: [PATCH] powerSet function --- src/Data/Set.purs | 7 +++++++ test/Test/Main.purs | 16 ++++++++++++++-- 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/src/Data/Set.purs b/src/Data/Set.purs index 0269cd5..b794c04 100644 --- a/src/Data/Set.purs +++ b/src/Data/Set.purs @@ -24,6 +24,7 @@ module Data.Set , subset , properSubset , intersection + , powerSet ) where import Prelude hiding (map) @@ -176,3 +177,9 @@ intersection s1 s2 = fromFoldable $ runPure (runSTArray (emptySTArray >>= inters LT -> pure $ Loop {a: l + 1, b: r} GT -> pure $ Loop {a: l, b: r + 1} else pure $ Done acc + +-- | The set of all subsets of the given set +powerSet :: forall a. Ord a => Set a -> Set (Set a) +powerSet = + foldl (\subPowerset a -> subPowerset `union` map (insert a) subPowerset) + (singleton empty) diff --git a/test/Test/Main.purs b/test/Test/Main.purs index 66c9e74..89e65b5 100644 --- a/test/Test/Main.purs +++ b/test/Test/Main.purs @@ -4,10 +4,9 @@ import Prelude import Control.Monad.Eff (Eff) import Control.Monad.Eff.Console (CONSOLE, log) -import Test.Assert (ASSERT, assert) - import Data.Set (Set) import Data.Set as S +import Test.Assert (ASSERT, assert) main :: Eff (console :: CONSOLE, assert :: ASSERT) Unit main = do @@ -26,3 +25,16 @@ main = do s2 = S.fromFoldable [2,4,6,8,10] s3 = S.fromFoldable [2,4] assert $ S.intersection s1 s2 == s3 + + log "powerSet" + do let set = S.fromFoldable [0, 1, 2] + assert $ S.powerSet set == (S.fromFoldable `S.map` S.fromFoldable [ + [] + , [0] + , [1] + , [2] + , [0,1] + , [0,2] + , [1,2] + , [0,1,2] + ])