Union of two sets in Scala

前端 未结 4 1698
说谎
说谎 2021-02-01 22:27

From the question linked here, I found this implementation of Union in Scala:

def union(a: Set, b: Set): Set = i => a(i) || b(i)

And Set is

4条回答
  •  你的背包
    2021-02-01 23:24

    And when it finds a match between to sets, it returns true, if it indeed does, where do I filter it?

    union does not find a match between two sets, it creates a new set which contains the values of both sets. Example:

    val a = (i) => i == 2 // a contains 2 as a(2) == True
    val b = (i) => i == 5 // b contains 5 as b(5) == True
    val u = union(a, b)   // u contains 2 and 5 as u(2) == True and u(5) == True
    

    So the 'filtering' just happens on the way. This function is not iterating over each set, filtering specific things out, it just returns a combination of two functions which then can executed later to query for the actual values.

    Example of querying the values of a union:

    val a = (i) => i == 2
    val b = (i) => i == 5
    val u = union(a, b)
    
    for(i <- 1 to 10 if u(i)) yield i     // returns Vector(2, 5)
    

    And yes, this is not an optimal way of storing values in sets as you have to check values by guessing but it is a good way to demonstrate how combining functions adds complex functionality without writing very complex code.

提交回复
热议问题