2

I was working on implementing a recursive powerset algorithm in Ruby and I came across this Stack Overflow post.

def powerset(set)
  return [set] if set.empty?

  p = set.pop
  subset = powerset(set)  
  subset | subset.map { |x| x | [p] }
end

powerset(['a'], ['b'], ['c']) ---> [[], ["a"], ["b"], ["a", "b"], ["c"], ["a", "c"], ["b", "c"], ["a", "b", "c"]]

Basically, I'm at a loss in understanding the last line. I understand that this is the 'bitwise or' operator, and I generally understand what this does, but I'm having a lot of trouble comprehending how it works in this last line works here.

Can someone show me what the equivalent would be in easier to read Ruby?

Max Millington
  • 4,378
  • 4
  • 27
  • 34
  • 6
    actually when used on arrays, `|` is the [`union` operator](https://ruby-doc.org/core-2.2.0/Array.html#method-i-7C) – Hamms Jul 31 '17 at 18:54
  • 1
    Ruby's operators always resolve to methods. If the receiver is an integer, then [`|`](http://ruby-doc.org/core-2.4.1/Integer.html#method-i-7C) is bitwise OR. But for arrays, it's set union. – Stefan Jul 31 '17 at 18:55
  • It would be nice if you could tell us, which *specific* part of the documentaiton of `Set#|` is unclear to you. That way, the Ruby developers can improve the documentation for future readers. – Jörg W Mittag Jul 31 '17 at 19:52
  • @JörgWMittag This doesn't have anything to do with the `Set` documentation. Looks like I mistakenly thought the `|` was a bitwise OR operator, which lead to my not understanding how it works in this situation. Whereas the `|` is actually a method on `Array` – Max Millington Jul 31 '17 at 19:57
  • Well, then the same question holds: what made you think that `Array#|` was a bitwise-OR? Is there something that can be improved in its documentation? – Jörg W Mittag Jul 31 '17 at 20:00

1 Answers1

1

Here's an equivalent in easier to read words :)

If the set is empty:
  return a list with one empty set

Remove an element from the set and call it "p"
Call "subset" the powerset of the new set (that excludes p)
Return the union of this new powerset and another
  version of it, where p is added to each of its sets
גלעד ברקן
  • 23,602
  • 3
  • 25
  • 61