Previous Entry Share Next Entry
03:07 pm, 23 Feb 07


Beautiful Haskell implementation of math's "power set":
import Control.Monad

powerset :: [a] -> [[a]]
powerset = filterM (const [True, False])

And powerset [1,2,3] produces [[1,2,3],[1,2],[1,3],[1],[2,3],[2],[3],[]].

Oh man is that hard for me to grok, mostly because I haven't internalized the list monad.
(It helped me to write out the definition of filterM, which has type Monad m => (a -> m Bool) -> [a] -> m [a].)

But roughly, it's saying "for each assignment of true and false over the values of the list, grab the true values".

[via Adam Langley via a private mailing list]