ktii
ktii

Reputation: 59

Scala - Find duplicates in list using pattern matching and recursion

I am trying to solve a beginner problem but can't reach the solution:

If any duplicates in list, return true, else false. Empty lists considered.

def duplicates(a: List[Int]): Boolean = {
  case Nil => false
  case x :: xs =>
    if(xs.contains(x)) true else false
}

But this doesn't work. And it's not recursive. It's just something where I wanted to start but I'm stuck. Please kindly help and try to avoid non-beginner solutions if reasonable.

Upvotes: 1

Views: 257

Answers (1)

Knows Not Much
Knows Not Much

Reputation: 31546

You need to call your function recursively. So if xs doesn't contain x, then call the function but with the remaining list.

def duplicates(a: List[Int]): Boolean = a match {
  case Nil => false
  case x :: xs =>
    if(xs.contains(x)) true else duplicates(xs)
}

Upvotes: 1

Related Questions