Skip to content
This repository was archived by the owner on Oct 4, 2020. It is now read-only.

Commit bdb54ee

Browse files
committed
powerset function
1 parent 2577352 commit bdb54ee

File tree

2 files changed

+21
-2
lines changed

2 files changed

+21
-2
lines changed

src/Data/Set.purs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ module Data.Set
2424
, subset
2525
, properSubset
2626
, intersection
27+
, powerset
2728
) where
2829

2930
import Prelude hiding (map)
@@ -176,3 +177,9 @@ intersection s1 s2 = fromFoldable $ runPure (runSTArray (emptySTArray >>= inters
176177
LT -> pure $ Loop {a: l + 1, b: r}
177178
GT -> pure $ Loop {a: l, b: r + 1}
178179
else pure $ Done acc
180+
181+
-- | The set of all subsets of the given set
182+
powerset :: forall a. Ord a => Set a -> Set (Set a)
183+
powerset =
184+
foldl (\subPowerset a -> subPowerset `union` map (insert a) subPowerset)
185+
(singleton empty)

test/Test/Main.purs

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,9 @@ import Prelude
44

55
import Control.Monad.Eff (Eff)
66
import Control.Monad.Eff.Console (CONSOLE, log)
7-
import Test.Assert (ASSERT, assert)
8-
97
import Data.Set (Set)
108
import Data.Set as S
9+
import Test.Assert (ASSERT, assert)
1110

1211
main :: Eff (console :: CONSOLE, assert :: ASSERT) Unit
1312
main = do
@@ -26,3 +25,16 @@ main = do
2625
s2 = S.fromFoldable [2,4,6,8,10]
2726
s3 = S.fromFoldable [2,4]
2827
assert $ S.intersection s1 s2 == s3
28+
29+
log "powerset"
30+
do let set = S.fromFoldable [0, 1, 2]
31+
assert $ S.powerset set == (S.fromFoldable `S.map` S.fromFoldable [
32+
[]
33+
, [0]
34+
, [1]
35+
, [2]
36+
, [0,1]
37+
, [0,2]
38+
, [1,2]
39+
, [0,1,2]
40+
])

0 commit comments

Comments
 (0)