You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Scala List[(Double, Double)]模式匹配实现带阈值的首元素累加

你需要给递归函数新增阈值参数,再通过模式匹配的条件守卫判断终止条件即可,实现如下:

基础递归实现(和你原有逻辑兼容)

// 新增threshold参数传入阈值
def sumUntilThreshold(xs: List[(Double, Double)], threshold: Double): Double = {
  xs match {
    // 条件守卫:当前元素第一个值大于阈值时直接返回0,停止递归
    case x :: _ if x._1 > threshold => 0
    // 否则累加当前值,继续处理尾部列表
    case x :: tail => x._1 + sumUntilThreshold(tail, threshold)
    case Nil => 0
  }
}

调用方式:sumUntilThreshold(compensation, 400),返回结果为700,符合需求。


推荐尾递归优化版本(避免长列表栈溢出)

import scala.annotation.tailrec

// 用累加器参数存储中间结果,编译器会优化为循环执行
@tailrec
def sumUntilThreshold(xs: List[(Double, Double)], threshold: Double, accumulator: Double = 0.0): Double = {
  xs match {
    case x :: _ if x._1 > threshold => accumulator
    case x :: tail => sumUntilThreshold(tail, threshold, accumulator + x._1)
    case Nil => accumulator
  }
}

标准库API极简实现

不需要手写递归,直接用Scala内置集合API即可完成需求,可读性更高:

val result = compensation.takeWhile(_._1 <= 400).map(_._1).sum

内容的提问来源于stack exchange,提问作者BiCCThor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 02:45:02