2017-01-14 1 views
0

collect과 같은 함수를 찾고 있습니다. 이 함수는 술어를 만족시키지 않는 요소를 유지해야합니다. 이 동작은 map을 사용하여 나타낼 수 있습니다. 예 :어떤 함수는 collect와 같은 동작을하지만 술어를 만족하지 않는 요소를 유지합니다.

@ (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$1.apply$mcII$sp(cmd4.sc:1) 
    $sess.cmd4$$anonfun$1.apply(cmd4.sc:1) 
    $sess.cmd4$$anonfun$1.apply(cmd4.sc:1) 
    scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:234) 
    scala.collection.TraversableLike$$anonfun$map$1.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) 

불행하게도, 내가 MatchErrors을 피하기 위해 PartialFunction을받는 함수 발견하지 않았습니다.

이러한 동작을하는 함수를 알고 있습니까?

답변

2

난 당신이 원하는 것을 미리 정의 된 방법이 있다고 생각하지 않지만, 당신이 그것을 할 수있는 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) 
0

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) 
+0

동의합니다. 'collect'와'map' (cf. 첫 번째 코드 스 니펫 참조)이 여기서 일을 할 수 있습니다. 그러나 나의 목표는이 줄을 피하는 것이었다 :'case e => e'. – Dnomyar

+0

왜 그냥'List (...). map (e> 5) e * e else e}'라고 써야할까요? 나는 암묵적인'mapIfDefined' 메쏘드를 사용하여 간단한'else' 절을 대체하는 것이 더 합리적이라고 생각합니다. – Eric

관련 문제