Union of two sets in Scala

前端 未结 4 1629
说谎
说谎 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:10

    The Set (which is just a function) that gets returned from union takes some integer as a parameter; you must give it an arbitrary name so that you can refer to it in the function body. It may make more sense if you write the function like this:

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

    It may make even more sense if you write it like this:

    def union(a: Set, b: Set): Set = {
      // The union of two sets is a new function that takes an Int...
      def theUnion(i: Int): Boolean = {
        // and returns true if EITEHR of the other functions are true
        a(i) || b(i)
      }
    
      // Now we want to return the NEW function
      theUnion
    }
    

    Again, i is arbitrary and could be replaced with any variable:

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

    [Update]

    Because we're representing sets as functions, there's no need to iterate to see if they contain a number. For example, here's a set that contains any number below -5:

    val belowNegFive: Set = (i) => i < -5
    

    When we call that function with a number, it will tell us if that number is in the set. Note that at no time did we actually tell it the specific numbers that were in the set:

    scala> belowNegFive(10)
    res0: Boolean = false
    
    scala> belowNegFive(-100)
    res1: Boolean = true
    
    scala> belowNegFive(-1)
    res2: Boolean = false
    

    Here's another set that includes any number between 50 and 100:

    val fiftyToHundred: Set = (i) => i >= 50 && i <= 100
    
    scala> fiftyToHundred(50)
    res3: Boolean = true
    
    scala> fiftyToHundred(100)
    res4: Boolean = true
    
    scala> fiftyToHundred(75)
    res5: Boolean = true
    
    scala> fiftyToHundred(49)
    res6: Boolean = false
    

    Now, a union of the sets belowNegFive and fiftyToHundred would contain any number that is either below -5 or between 50 and 100. We can easily represent this in code by returning a new function which itself returns true if either of the other two functions returns true.

    scala> val unionOfBoth: Set = (i) => belowNegFive(i) || fiftyToHundred(i)
    unionOfBoth: Int => Boolean = 
    
    scala> unionOfBoth(-10)
    res7: Boolean = true
    
    scala> unionOfBoth(50)
    res8: Boolean = true
    
    scala> unionOfBoth(0)
    res9: Boolean = false
    

    The union function from your question is just a way of applying this pattern generically over any two sets.

提交回复
热议问题