Functional Programming: Does a list only contain unique items?

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

提交回复
热议问题