Union of two sets in Scala

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

    You can implement a union function like this:

    def union[A](set1: Set[A], set2:Set[A]):Set[A] = {
        set1.foldLeft(set2)((set, elem) => set + elem)
    }
    

    or

    def union[A](set1: Set[A], set2:Set[A]):Set[A] = {
        set1.flatMap(elem => set2 + elem)
    }
    

    These will be generic so you can use it for sets of any type

提交回复
热议问题