Click here to Skip to main content
Click here to Skip to main content

Generating the Powerset of a Set

By , 1 Feb 2013
 

Introduction

A quick way to generate the powerset of a set in F#. Useful for solving combinatorial problems.

Using the code

Simply copy and paste and fire away!

let powerset l =
    let s = ((l |> List.length) |> pown 2) - 1
    [0..s] |> 
    List.map (fun i -> l |> 
                       List.mapi (fun a b -> if (pown 2 a) &&& i <> 0 then Some(b) else None) |> 
                       List.choose id)


// powerset [1;2;3] = [[]; [1]; [2]; [1; 2]; [3]; [1; 3]; [2; 3]; [1; 2; 3]]

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Muigai Mwaura
Technical Lead Olivine Technology
Kenya Kenya
Member
Technical Lead, Olivine Technology - Nairobi, Kenya.
 
"The bane of productivity: confusing the rituals of work (sitting at your desk by 8:00am, wearing a clean and well pressed business costume etc.) with actual work that produces results."
 
Watch me!

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
Questionsome fixesmemberthelazydogsback7 Feb '13 - 8:57 
AnswerRe: some fixesmemberMuigai Mwaura7 Feb '13 - 10:24 
Cool a substantial improvement.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130516.1 | Last Updated 1 Feb 2013
Article Copyright 2013 by Muigai Mwaura
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid