[Haskell-beginners] Powerset function

Shishir Srivastava shishir.srivastava at gmail.com
Tue Apr 21 14:56:50 UTC 2015


Hi,

In the 'learnyouahaskell' online book the powerset function is described
like this -

----
powerset :: [a] -> [[a]]
powerset xs = filterM (\x -> [True, False]) xs
----

And the filterM function is defined like this

filterM :: (Monad m) => (a -> m Bool) -> [a] -> m [a]

--

The filterM function is said to be an extension of 'filter' function which
maps the monadic predicate over the given list.

Now in powerset function the predicate returns a monad [True,False] for
every element of the given list.

So for e.g. if the input list was only [1] the output of filterM will
understandably be the cartesian product of [True, False] x [1] = [[1], []].

Extending this if the given input list contains two elements [1,2] the
predicate would be mapped one by one on each of the elements and the result
combined which means the output should be

[[1], [], [2], []]

But the powerset of [1,2] is definitely not that.

Please could someone help me in getting my head around with how filterM is
working in this case.

Thanks,
Shishir
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/beginners/attachments/20150421/fe6622f1/attachment.html>


More information about the Beginners mailing list