我在List [(Int,Double)]收集了一些财务数据,如下所示:
val snp = List((2001, -13.0), (2002, -23.4))
有了这个,我写了一个公式,将列表,通过地图,转换成另一个列表(以证明投资等级人寿保险),其中低于0的损失转换为0,高于15的增益转换为15,如这样:
case class EiulLimits(lower:Double, upper:Double)
def eiul(xs: Seq[(Int, Double)], limits:EiulLimits): Seq[(Int, Double)] = {
xs.map(item => (item._1,
if (item._2 < limits.lower) limits.lower
else if (item._2 > limits.upper) limits.upper
else item._2
}
无论如何都要在其中提取元组的值,所以我不必使用笨重的_1和_2表示法吗?
答案 0 :(得分:8)
List((1,2),(3,4)).map { case (a,b) => ... }
case
关键字调用模式匹配/取消应用逻辑。
请注意在map
更快但更短的快速重写代码:
case class EiulLimits(lower: Double, upper: Double) {
def apply(x: Double) = List(x, lower, upper).sorted.apply(1)
}
def eiul(xs: Seq[(Int, Double)], limits: EiulLimits) = {
xs.map { case (a,b) => (a, limits(b)) }
}
用法:
scala> eiul(List((1, 1.), (3, 3.), (4, 4.), (9, 9.)), EiulLimits(3., 7.))
res7: Seq[(Int, Double)] = List((1,3.0), (3,3.0), (4,4.0), (7,7.0), (9,7.0))
答案 1 :(得分:0)
scala> val snp = List((2001, -13.0), (2002, -23.4))
snp: List[(Int, Double)] = List((2001,-13.0), (2002,-23.4))
scala> snp.map {case (_, x) => x}
res2: List[Double] = List(-13.0, -23.4)
scala> snp.map {case (x, _) => x}
res3: List[Int] = List(2001, 2002)