With scala, can I unapply a tuple and then run a map over it?

≡放荡痞女 提交于 2020-01-03 13:04:26

问题


I have some financial data gathered at a List[(Int, Double)], like this:

val snp = List((2001, -13.0), (2002, -23.4))

With this, I wrote a formula that would transform the list, through map, into another list (to demonstrate investment grade life insurance), where losses below 0 are converted to 0, and gains above 15 are converted to 15, like this:

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
}

Is there anyway to extract the tuple's values inside this, so I don't have to use the clunky _1 and _2 notation?


回答1:


List((1,2),(3,4)).map { case (a,b) => ... }

The case keyword invokes the pattern matching/unapply logic.

Note the use of curly braces instead of parens after map


And a slower but shorter quick rewrite of your code:

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)) } 
}

Usage:

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



回答2:


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)


来源:https://stackoverflow.com/questions/9913665/with-scala-can-i-unapply-a-tuple-and-then-run-a-map-over-it

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!