Powerset of a set with list comprehension in Haskell

user3059248 picture user3059248 · Sep 15, 2015 · Viewed 8.7k times · Source

I am a complete beginner in Haskell and I have 11 exercises for homework, 10 of which I have already solved. I have found several solutions to get the powerset of a set, but none of them includes list comprehension. I know I should not ask for a complete answer in this case (because it is homework) but I would very much appreciate any feedback/clue.

The powerset of set S is a set containing all subsets of S. Write a recursive function powerset that returns a set containing all subsets of a given set. Use direct recursion and list comprehension.

Answer

Michael McKenna picture Michael McKenna · Sep 16, 2016

Using direct recursion and list comprehension:

type Set a = [a]

powerset :: Set a -> Set (Set a)
powerset [] = [[]]
powerset (x:xs) = [x:ps | ps <- powerset xs] ++ powerset xs