BufBills
BufBills

Reputation: 8103

scala filter of 2 sets

  def intersect(s: Set, t: Set): Set = (x => s(x) && t(x))


  def filter(s: Set, p: Int => Boolean): Set  = intersect(s, p)

I have this code. I don't understand how does "filter" function be a valid one. First of all, it uses intersect, but second parameter p is a method, not a Set as intersect function prototype requres. Secondly, how does intersect(s, p) work as filter?

thanks

Upvotes: 1

Views: 811

Answers (1)

Travis Brown
Travis Brown

Reputation: 139038

These are two different ways of looking at the same thing. As I mentioned in my previous answer, representing sets as their indicator functions makes lots of things more convenient, and one of those things is filtering.

Usually when we have a collection of some type A we can filter it using a predicate function A => Boolean that tells us whether or not we want to keep each element. In this case, the type of the predicate function is the same type we're using to represent the collection, and filtering is the same thing as taking the intersection of two sets.

To address your second question: intersect needs to return a function that will return true if the item is in both set s and set t and false otherwise. We can check that using the apply method on each (or in this case its syntactic sugar). The implementation is then a simple function literal (x => s(x) && t(x)) that takes an argument x and returns true if and only if x is in both sets.

Upvotes: 2

Related Questions