Description
I miss having a form of filter
that takes a partial function. It feels really natural to me to be able to write
List(1, 2, 3, 4, 5, 6).filter {
case i if i > 3 => i % 2 == 0
}
resulting in List(4, 6)
Of course, you could use collect
for that case and move the rhs of the pattern to the guard, but quite often, the expression is more complex, and you really want to use a block.
A definition for that could be def filter(pf: PartialFunction[A, Boolean]) = filter(pf.applyOrElse(_, _ => false)
(though adding this by extension probably isn't possible since an applicable method already exists in "classic" filter).
I find the same thing lacking for something between collect and flatMap: I'd love a def flatCollect[B](pf: PartialFunction[A, B]) = flatMap(pf.applyOrElse(_, _ => empty))
. In action:
List(1, 2, 3, 4, 5, 6).flatCollect {
case i if i > 3 => List(i, i)
}
// List(4, 4, 6, 6)
other potential partial variations of functions that I can kinda see but don't have strong feelings about:
def mapPartial[A1 >: A](pf: PartialFunction[A, A1]) = map(pf.applyOrElse(_, identity))
def flatMapPartial[A1 >: A](pf: PartialFunction[A, CC[A1]]) = flatMap(pf.applyOrElse(_, x => x +: empty)
WDYT?