Functional Programming: Does a list only contain unique items?

后端 未结 3 1557
北海茫月
北海茫月 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:19

    Here is the fastest purely functional solution I can think of:

    def isUniqueList(l: List[T]) = isUniqueList1(l, new HashSet[T])
    
    @tailrec
    def isUniqueList1(l: List[T], s: Set[T]) = l match {
      case Nil => true
      case (h :: t) => if (s(h)) false else isUniqueList1(t, s + h)
    }
    

    This should be faster, but uses mutable data structure (based on the distinct implementation given by Vasil Remeniuk):

    def isUniqueList(l: List[T]): Boolean = {
      val seen = mutable.HashSet[A]()
      for (x <- this) {
        if (seen(x)) {
          return false
        }
        else {
          seen += x
        }
      }
      true
    }
    

    And here is the simplest (equivalent to yours):

    def isUniqueList(l: List[T]) = l.toSet.size == l.size
    
    0 讨论(0)
  • 2021-02-14 04:23

    A more efficient method would be to attempt to find a dupe; this would return more quickly if one were found:

    var dupes : Set[A] = Set.empty
    
    def isDupe(a : A) = if (dupes(a)) true else { dupes += a; false }
    
    //then
    l exists isDupe 
    
    0 讨论(0)
  • 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
      }
    
    0 讨论(0)
提交回复
热议问题