I have three Scala regular expressions that I need to test to see if any of them matches a given String.
I know that I can do the following:
val matches = R1.findFirstIn(myString).isDefined ||
R2.findFirstIn(myString).isDefined ||
R3.findFirstIn(myString).isDefined
but I believe that there is a way to do this using an Applicative Functor or Monad from the Scalaz library.
How can this be done?
This is the sum under the “first” (or “last”) monoid instance for
Option. In Scalaz 7 you can write:Or, alternatively:
Note that both of these solutions return the match itself, which you can of course call
isDefinedon if you want the same behavior as in your implementation.As a side note, the
|+|for the first monoid instance here is justorElsein the standard library, so you can write this almost as succinctly without Scalaz:Which is of course not an argument against using Scalaz, since it lets us capture the abstraction more cleanly, and provides an elegant way to change the behavior with regard to whether the first or last
Someis returned.