Functional Programming: Does a list only contain unique items?

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

提交回复
热议问题