Search code examples
hacklang

Hack language - Set intersection


The Hack Set has a difference method but I don't see a method called intersect or any similar one.

How to get an intersection of two sets?

$set1 = Set { 'a', 'x' };
$set2 = Set { 'b', 'c', 'x', 'y' };
$intersection = ??? // Set { 'x' }

Docs: https://docs.hhvm.com/hack/reference/class/HH.Set/


Solution

  • I'm not sure why that function doesn't exist, but you can put this code in some utility function:

      $intersection = Set {};
      foreach ($other as $v) {
        if ($set->contains($v)) {
          $intersection->add($v);
        }
      }
    

    Additionally, you can add a check so you iterate the smaller set.

    OR, if you like one liners, this also works :)

    $set1->filter($x ==> $set2->contains($x))