Peter
Peter

Reputation: 6035

Using Scala pattern matching to find whether a List contains a value

I've seen a range of different matches you can do against a List using pattern matching. Is it possible to use pattern matching to identify if any (and ideally which) element in a list contains value x? So something like this:

def contains(text: List[Char], chr: Char): Boolean = text match{
  case *pattern matching chr to any value in text* => true
  case _ => false
}

Just trying to learn what it can and can't do.

(I know I can use text.contains(chr), BTW)

Thanks, Peter

Upvotes: 0

Views: 5172

Answers (2)

RomanI
RomanI

Reputation: 403

not sure if that what you are looking for, but you can put if expressions in pattern matching.

this code looks artificial, but it demonstrates how to put contains or other random functions in pattern matching.

scala> def contains(text: List[Char], chr: Char): Boolean = text match{
     |     case _ if text.contains(chr) => true
     |     case _ => false
     | }
contains: (text: List[Char], chr: Char)Boolean

scala> contains(List('a', 'b', 'c'), 'd')
res2: Boolean = false

scala> contains(List('a', 'b', 'c'), 'c')
res3: Boolean = true

Upvotes: 1

Ende Neu
Ende Neu

Reputation: 15773

What I have seen is use matching on list to recurse, in your case something like this probably:

def contains(text: List[Char], chr: Char): Boolean = text match{
  case head :: tail  => head.equals(chr) || contains(tail, chr)
  case Nil => false
}

I don't think you can use the match to do this kind of operations because of how the unapply method of list is defined, theoretically if you know the length of the list you could write something like

case x1 :: x2 :: x3 // and so on

But I guess you can see by yourself that this is not practical nor ideal for param-matching.

Upvotes: 1

Related Questions