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

powerSet function #44

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions src/Data/Set.purs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ module Data.Set
, subset
, properSubset
, intersection
, powerSet
) where

import Prelude hiding (map)
Expand Down Expand Up @@ -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)
16 changes: 14 additions & 2 deletions test/Test/Main.purs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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]
])