Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check a string against a symbols whitelist a functional way in Scala?

Tags:

string

scala

I need to guarantee a string only contains allowed symbols. Now I do it this way:

def isCorrect(s: String, allowedChars: String): Boolean = {
  s.distinct.foreach(c => {
    if (!allowedChars.contains(c))
      return false
  })

  true
}

Needless to say this does not look too pretty. Is there a better, more functional way to do this?

like image 205
Ivan Avatar asked Nov 28 '22 17:11

Ivan


1 Answers

For the record, you can make this a little more generic by not limiting yourself to strings of characters, and a little more functional (in my view) by switching the order of arguments and using two argument lists. Here's how I'd write it:

def isCorrect[A](allowed: Set[A])(s: Seq[A]) = s forall allowed

Now you can treat this method as a function and "partially apply" it to create more specialized functions:

val isDigits = isCorrect("0123456789".toSet) _
val isAs = isCorrect(Set('A')) _

Which allows you to do the following:

scala> isDigits("218903")
res1: Boolean = true

scala> isAs("218903")
res2: Boolean = false

scala> isDigits("AAAAAAA")
res3: Boolean = false

scala> isAs("AAAAAAA")
res4: Boolean = true

Or you could still just use something like isCorrect("abcdr".toSet)("abracadabra").

like image 77
Travis Brown Avatar answered Dec 22 '22 07:12

Travis Brown