如何简化这种模式匹配?

时间:2016-06-02 13:50:15

标签: scala pattern-matching

假设我有这样的功能:

def foo(x: Int): Int = ???

def bar(xs: List[Int]): List[Int] = xs map {
  case x if (x > 0) => x
  case x if (foo(x) > 0) => foo(x) + 1
  case _ => 0 
}

问题是foo被称为两次。您如何撰写bar仅拨打foo一次?

2 个答案:

答案 0 :(得分:5)

def foo(x: Int): Int = ???

def bar(xs: List[Int]): List[Int] = xs.map {
   x =>
     lazy val food = foo(x)
     if(x > 0) x
     else if (food > 0) food + 1
     else 0
}

答案 1 :(得分:4)

case x => 
  val y = foo(x) 
  if(y > 0) y + 1 else 0

map两次:

 list
   .map {
     case x if x > 0 => x
     case x => foo(x) + 1
   }.map { 
     case x if x < 0 => 0
     case x => x
   }

或者将foo包装到Option,并过滤:

 ... 
 case x => Option(foo(x) + 1).filterNot(_ < 0).getOrElse(0)