How to generate the power set of a set in Scala

前端 未结 8 1948
佛祖请我去吃肉
佛祖请我去吃肉 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:31

    Here's a simple, recursive solution using a helper function:

    def concatElemToList[A](a: A, list: List[A]): List[Any] = (a,list) match {
        case (x, Nil)                 => List(List(x))
        case (x, ((h:List[_]) :: t))  => (x :: h) :: concatElemToList(x, t)
        case (x, (h::t))              => List(x, h) :: concatElemToList(x, t)
    }
    
    def powerSetRec[A] (a: List[A]): List[Any] = a match {
        case Nil    => List()
        case (h::t) => powerSetRec(t) ++ concatElemToList(h, powerSetRec (t))
    }
    

    so the call of

    powerSetRec(List("a", "b", "c"))
    

    will give the result

    List(List(c), List(b, c), List(b), List(a, c), List(a, b, c), List(a, b), List(a))
    
    0 讨论(0)
  • 2020-12-13 15:33

    Looks like no-one knew about it back in July, but there's a built-in method: subsets.

    scala> Set(1,2,3).subsets foreach println
    Set()
    Set(1)
    Set(2)
    Set(3)
    Set(1, 2)
    Set(1, 3)
    Set(2, 3)
    Set(1, 2, 3)
    
    0 讨论(0)
提交回复
热议问题