1
\$\begingroup\$

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?

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

Your Answer

By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.