+7  A: 

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
  }
Vasil Remeniuk
+1 for distinct, but wouldn't `l.distinct.size == l.size` be O(1) instead of O(n) for the comparison?
tstenner
Agreed, edited, thank you :)
Vasil Remeniuk
No, since `List.size` is itself O(n). See http://lampsvn.epfl.ch/trac/scala/browser/scala/tags/R_2_8_0_final/src//library/scala/collection/immutable/List.scala#L1 to check that size has to be calculated by iterating over the list.
Alexey Romanov
You're right, but List.size can be implemented as O(1) whereas it's impractical for comparison.
tstenner
+11  A: 

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
Alexey Romanov
Cool, good answer
Vasil Remeniuk
you can change the `if (s.contains(h)) false else isUniqueList1(t, s + h)` to: `!(s(h) || !isUniqueList(t, s + h))`
oxbow_lakes
Alexey Romanov
good point, Alexey
oxbow_lakes
+2  A: 

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 
oxbow_lakes