Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Idiomatic way to implement containsAny for Scala SeqLike

Tags:

scala

Scala's SeqLike implement a method contains. How can I cleanly implement a containsAny feature?

Let's say I want to find out if a string string contains any of the blacklisted characters in blacklist:

val blacklist = List("(", ")", "[", "]", "{", "}", "<", ">")
string containsAny blacklist

How is the best way to implement the second line cleanly?

My version so far looks like this:

(blacklist.view map string.contains) contains true
like image 306
notan3xit Avatar asked Mar 23 '13 15:03

notan3xit


1 Answers

Your best bet is to make the blacklist a set.

val blacklist = "()[]{}<>".toSet

Now you can use exists to find if any of those characters exist in your string. Since Set[T] extends T => Boolean, you can just use the set directly instead of having to write an explicit condition.

scala> "I like fish (but not herring)" exists blacklist
res1: Boolean = true

scala> "I like fish, especially salmon!" exists blacklist
res2: Boolean = false

(Note: be careful about the difference between strings, "I am a string" and characters: 'c'. A one-character string is a string, not a character.)

like image 160
Rex Kerr Avatar answered Oct 14 '22 03:10

Rex Kerr