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?
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")
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With