Functional Programming: Does a list only contain unique items?

后端 未结 3 1565
北海茫月
北海茫月 2021-02-14 03:55

I\'m having an unsorted list and want to know, whether all items in it are unique.
My naive approach would be

val l = List(1,2,3,4,3)
def isUniqueList(l: List[Int         


        
3条回答
  •  粉色の甜心
    2021-02-14 04:30

    I would simply use distinct method:

    scala> val l = List(1,2,3,4,3)
    l: List[Int] = List(1, 2, 3, 4, 3)
    
    scala> l.distinct.size == l.size
    res2: Boolean = false
    


    ADD: Standard distinct implementation (from scala.collection.SeqLike) uses mutable HashSet, to find duplicate elements:

      def distinct: Repr = {
        val b = newBuilder
        val seen = mutable.HashSet[A]()
        for (x <- this) {
          if (!seen(x)) {
            b += x
            seen += x
          }
        }
        b.result
      }
    

提交回复
热议问题