Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

tuples

scala

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?

like image 320
gregturn Avatar asked Mar 28 '12 18:03

gregturn


1 Answers

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))
like image 171
dhg Avatar answered Sep 28 '22 19:09

dhg