How to check a string with a character whose whitelist is a functional way in Scala?

I need to ensure that the string contains only valid characters. Now I do it like this:

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?

+4
source share
4 answers

I don't know if this is the most functional way, but you can do it:

 def isCorrect(s: String, allowedChars: String): Boolean = { return s.distinct.forall(c => allowedChars.contains(c)) } 

excellent is not needed.

+2
source

For the record, you can make this a little more general without restricting yourself to line characters and a little more functional (in my opinion), switching the order of the arguments and using two lists of arguments. Here's how I write it:

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

Now you can consider 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 can just use something like isCorrect("abcdr".toSet)("abracadabra") .

+18
source
 def isCorrect(s:String, allowedChars:String):Boolean = { s.forall{allowedChars.contains(_)} } 

Or, even more succinctly, following @ziggystar's suggestion:

 def isCorrect(s: String, allowedChars: Seq[Char]) = s forall allowedChars.contains 
+4
source

This is no more functional, but uses regexp:

 def isCorrect(s: String, allowedChars: String): Boolean = s.matches ("^["+ allowedChars +"]*$") 

Since regex is often optimized, I would consider this approach in performance-critical code - not without testing, measuring, and possibly with pre-compiled templates - if necessary for the problem.

As a more functional flavor, I see the Travis code.

+2
source

Source: https://habr.com/ru/post/969847/


All Articles