I was informed that I am using this interesting piece of code, but my use case requires it to do a little more than is currently possible.
implicit class Predicate[A](val pred: A => Boolean) {
def apply(x: A) = pred(x)
def &&(that: A => Boolean) = new Predicate[A](x => pred(x) && that(x))
def ||(that: A => Boolean) = new Predicate[A](x => pred(x) || that(x))
def unary_! = new Predicate[A](x => !pred(x))
}
Some usage patterns:
type StringFilter = (String) => Boolean
def nameFilter(value: String): StringFilter =
(s: String) => s == value
def lengthFilter(length: Int): StringFilter =
(s: String) => s.length == length
val list = List("Apple", "Orange", "Meat")
val isFruit = nameFilter("Apple") || nameFilter("Orange")
val isShort = lengthFilter(5)
list.filter { (isFruit && isShort) (_) }
So far, everything is working fine. But say that I want to do something like this:
val nameOption: Option[String]
val lengthOption: Option[Int]
val filters = {
nameOption.map((name) =>
nameFilter(name)
) &&
lengthOption.map((length) =>
lengthFilter(length)
)
}
list.filter { filters (_) }
So now I need &&a Option[(A) => Boolean]If the parameter is None, just ignore the filter.
If I use something like:
def const(res:Boolean)[A]:A=>Boolean = a => res
implicit def optToFilter[A](optFilter:Option[A => Boolean]):A => Boolean = optFilter match {
case Some(filter) => filter
case None => const(true)[A]
}
I have a problem ||with one filter set to true. I can solve this by changing true to false, but then there is the same problem with &&.
I could also take this approach:
implicit def optionalPredicate[A](pred: Option[A => Boolean]): OptionalPredicate[A] = new OptionalPredicate(pred)
class OptionalPredicate[A](val pred: Option[A => Boolean]) {
def apply(x: A) = pred match {
case Some(filter) => filter(x)
case None => trueFilter(x)
}
def &&(that: Option[A => Boolean]) = Some((x: A) =>
pred.getOrElse(trueFilter)(x) && that.getOrElse(trueFilter)(x))
def ||(that: Option[A => Boolean]) = Some((x: A) =>
pred.getOrElse(falseFilter)(x) || that.getOrElse(falseFilter)(x))
}
def trueFilter[A]: A => Boolean = const(res = true)
def falseFilter[A]: A => Boolean = const(res = false)
def const[A](res: Boolean): A => Boolean = a => res
But something seems initially wrong in that you need to convert the Predicate to Optional Predicate when the predicate is not a child option type:
implicit def convertSimpleFilter[A](filter: A => Boolean) = Some(filter)
:
ifFruit && isShort
, Predicate, DRY.