DEV Community

Discussion on: Build a PowerSet

Collapse
 
carstenk_dev profile image
Carsten

depends on what you want to log I guess (seems doubtful, that you want to log anything here - indeed I never had the need to log anything inside a pure function as you can test it anytime if you know the input to it)

but sure most of us learned programming in the more operational/imperative mindset (basically by doing step-by-step debugging in our head) so it might take some time to get "warm" with FP ;)

But in those more mathematical problems (where the problem often is recursive in nature) it's just a natural fit ;)

Thread Thread
 
tomerbendavid profile image
Tomer Ben David • Edited

cool, adding the scala functional :: recursive :: declarative :: concise way to the post :)) .

  def powerSet(set: Set[Int]): Set[Set[Int]] = {

    set.toList match {
      case Nil => Set(Set.empty[Int])
      case x :: xs => powerSet(xs.toSet).map(xsi => xsi + x) ++ powerSet(xs.toSet)
    }
  }

  println(powerSet(Set(1,2,3))) // Set(Set(), Set(3, 1), Set(2), Set(2, 1), Set(3, 2), Set(3), Set(3, 2, 1), Set(1))