Before you start reading and understanding the bits and nuances of the above snippet, I would like
to stress on the point that while this code is algorithmically correct, looking at it doesn’t give you any information about the
definition of a powerset. It represents the thought process that would go through your mind while
building the powerset one by one at a time.

While this approach works well for most people, declarative languages use a separate way of expressing this problem. It is more of a top
down approach of expressing your problem statement and defining it in terms of functions which recursively generates the answers for you.

In Haskell the solution to the same question looks like this:

powerset=filterM(const[True,False])

And thats it!

The main motivation of this article is to explain what is going on above, as it might not be immediately apparent that how is the recursive machinery operating underneath. But what a beautiful and elegant looking function!!

First of all this is written in point free style Haskell.

The way to understand this definition is to study the source code of filterM.

Before going through it step by step lets us understand the 2 most important catches in the definition of filterM.

First for beginners who haven’t used the do notation in monads.

This step:

b<-px

when applied, will result in [True,False]. In the first iteration b assumes the value of True and then False and follows by concatenating the results of the two. The definition of bind for the List monad will help you understand more:

This is how the call stack would proceed and end up constructing the powerset for you.

Keep in mind this is not just another functional construct but a testament to the beauty and elegance you can attain while writing in Haskell. In most other functional languages including Clojure it would not be possible
to express this operation so succintly. Even in Scala you would have to resort to Scalaz to express this operation. This is owing to the flexibility of the do notation in Haskell, and while other languages might support monads but Haskell syntax makes it all the more fun and idiomatic to use!