哪个函数具有与 collect 相同的行为但保留不满足谓词的元素

Which function has the same behaviour as collect but keep the elements that do not satisfy the predicate

我正在寻找类似于 collect 的函数。此函数必须保留不满足谓词的元素。 这种行为可以使用 map 来表达。示例:

@ (0 to 10).map{
      case e if e > 5 => e * e
      case e          => e // I want to keep elements to does not satisfy the predicate !
  } 
res3: collection.immutable.IndexedSeq[Int] = Vector(0, 1, 2, 3, 4, 5, 36, 49, 64, 81, 100)

我希望能够像这样编写这个函数:

@ (0 to 10).map{
      case e if e > 5 => e * e
  } 
scala.MatchError: 0 (of class java.lang.Integer)
  $sess.cmd4$$anonfun.apply$mcII$sp(cmd4.sc:1)
  $sess.cmd4$$anonfun.apply(cmd4.sc:1)
  $sess.cmd4$$anonfun.apply(cmd4.sc:1)
  scala.collection.TraversableLike$$anonfun$map.apply(TraversableLike.scala:234)
  scala.collection.TraversableLike$$anonfun$map.apply(TraversableLike.scala:234)
  scala.collection.immutable.Range.foreach(Range.scala:160)
  scala.collection.TraversableLike$class.map(TraversableLike.scala:234)
  scala.collection.AbstractTraversable.map(Traversable.scala:104)
  $sess.cmd4$.<init>(cmd4.sc:1)
  $sess.cmd4$.<clinit>(cmd4.sc:-1)

不幸的是,我还没有找到需要 PartialFunction 来避免 MatchErrors 的函数。

你知道有这种行为的函数吗?

我认为没有 pre-defined 方法可以满足您的需求,但您可以使用 PartialFunction.applyOrElse 来实现:

scala> implicit class MySeq[A](r: Seq[A]) {
         def mapIfDefined(f: PartialFunction[A, A]): Seq[A] = {
           r.map(f.applyOrElse[A, A](_, identity))
         }
       }

scala> (0 to 10).mapIfDefined{
         case e if e > 5 => e * e
       }
res1: Seq[Int] = Vector(0, 1, 2, 3, 4, 5, 36, 49, 64, 81, 100)

除非我弄错了,collect 完全按照您的要求进行:

scala> List(1,2,3,4,5,6,7,8,9,10).collect {
     |   case e if e > 5 => e * e
     |   case e => e
     | }
res0: List[Int] = List(1, 2, 3, 4, 5, 36, 49, 64, 81, 100)