thomolando
thomolando

Reputation: 19

Is it possible to use an if-else construct in a pattern match in Scala?

So this is a small Scala function which checks if a given List contains a given Char :

def contains: (List[Char], Char) => Boolean = {
    case (Nil, c) => false
    case (cs, c) if cs.head == c => true
    case (cs, c) if cs.head != c => contains(cs.tail, c)
  }

Now I was wondering if or rather how I could simplify the cases and have it be something like:

def contains: (List[Char], Char) => Boolean = {
    case (Nil, c) => false
    case (cs, c) if cs.head == c => true
                 else => contains(cs.tail,c)
  }

Upvotes: 1

Views: 1484

Answers (1)

Guru Stron
Guru Stron

Reputation: 143513

The third case clause will be hit only if none of the first two matches, so you function effectively matches:

def contains: (List[Char], Char) => Boolean = {
    case (Nil, _) => false
    case (cs, c) if cs.head == c => true
    case (cs, c) => contains(cs.tail, c)
}

Note that in this particular case you can merge the last two cases by just using boolean logic:

def contains: (List[Char], Char) => Boolean = {
    case (Nil, _) => false
    case (cs, c) => cs.head == c || contains(cs.tail, c)
}

Upvotes: 3

Related Questions