# F# Finding the powerset of a set

I have this function which takes a list as input and computes the powerset.

let rec powerset = function
| []    -> [[]]
| x::xs -> List.collect (fun subset -> [subset; x::subset]) (powerset xs)

let ps = powerset [1..3]
val ps: int list list =
[[]; [1]; [2]; [1; 2]; [3]; [1; 3]; [2; 3]; [1; 2; 3]]


Is there a cleaner way to do it? I'm also a little confused by how it actually works. List.collect takes a function and a list and concats the results into a new list, which is then returned. But I have a little trouble following the flow in this case.

Why is the first list empty?

• Is that your code or are you asking for an explanation of someone else's code? – Martin R Nov 11 '17 at 20:39
• It's a function I found and modified slightly when searching for a way to find the powerset. – Left4Cookies Nov 11 '17 at 20:42
• it's seems like not appropriate Q for CR – user110704 Nov 15 '17 at 15:21