对列表的所有元素进行算术运算

时间:2019-01-04 08:57:11

标签: scala list math

我想问一下如何对列表进行算术运算。

减,除,乘

private def arithmeticOperations(leavesValues: List[Double]): Double = {
  op match {
    case '+' => leavesValues.sum
    case '-' => 0.0
    case '*' => 0.0
    case '/' => 0.0
    case _ => 0.0
  }
}

零值应替换为操作

1 个答案:

答案 0 :(得分:4)

private def arithmeticOperations(leavesValues: List[Double]): Double = {
  op match {
    case '+' => leavesValues.reduce(_ + _)
    case '-' => leavesValues.reduce(_ - _)
    case '*' => leavesValues.reduce(_ * _)
    case '/' => leavesValues.reduce(_ / _)
    case _ => 0.0
  }
}