How to generate the power set of a set in Scala

前端 未结 8 1949
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-13 14:41

I have a Set of items of some type and want to generate its power set.

I searched the web and couldn\'t find any Scala code that adresses this specific task.

8条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-13 15:28

    Here's one of the more interesting ways to write it:

    import scalaz._, Scalaz._
    
    def powerSet[A](xs: List[A]) = xs filterM (_ => true :: false :: Nil)
    

    Which works as expected:

    scala> powerSet(List(1, 2, 3)) foreach println
    List(1, 2, 3)
    List(1, 2)
    List(1, 3)
    List(1)
    List(2, 3)
    List(2)
    List(3)
    List()
    

    See for example this discussion thread for an explanation of how it works.

    (And as debilski notes in the comments, ListW also pimps powerset onto List, but that's no fun.)

提交回复
热议问题