With scala, can I delete a tuple and then run a map above it?

I have some financial data collected in List [(Int, Double)], for example:

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

With this, I wrote a formula that converts a list through a card to another list (to demonstrate life insurance in an investment class), where losses below 0 are converted to 0, and profits above 15 are converted to 15, for example 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 } 

Anyway, to extract the values ​​of the tuple inside this, so that I don’t need to use the clumsy notations _1 and _2?

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

The case keyword invokes pattern matching / incompatibility logic.

Note the use of curly braces instead of paren after map


And slower, but shorter, to quickly rewrite 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)) } } 

Using:

 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)) 
+8
source
 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) 
0
source

Source: https://habr.com/ru/post/1403978/


All Articles