1

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.

1 Answer 1

1

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)
}
Sign up to request clarification or add additional context in comments.

3 Comments

Sorry, I downvoted by mistake and can't upvote unless an edit is made.
It works, and I understand the duplicates(xs) in the end. But I don't understand why this 'a match' has to be there and why it resulted in error with 'false' in the end instead of duplicats(xs). Even if in the last case it would have been incorrect result, I still see it should have worked. Where I'm thinking wrong?
Ok, understood 'match' now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.