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

Commit

Permalink
powerset function
Browse files Browse the repository at this point in the history
  • Loading branch information
matthewleon committed Jan 15, 2018
1 parent 2577352 commit bdb54ee
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
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]
])

0 comments on commit bdb54ee

Please sign in to comment.