Last active
May 3, 2018 20:39
-
-
Save angerman/b70a53dac23d76602da6 to your computer and use it in GitHub Desktop.
Powersets in Haskell
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
powerset :: [a] -> [[a]] | |
powerset [] = [[]] | |
powerset (x:xs) = map (x:) (powerset xs) ++ powerset xs |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@chrisbloecker Internally
filterM
is doing something very similar to what @angerman's version is doing. TheTrue
andFalse
are the 2 cases. A list monad essentially represents non-determinism, and hence it takes all the cases. So here[True,False]
,filterM
will happen for bothTrue
as well asFalse
. When the predicate isTrue
it takes the first branch (map (x:) (powerset xs)
) and when it isFalse
it takes the second branchpowerset xs
.It is quite simple to grok if you observe 2 things:
filterM
function