D.L. - 2 months ago 7
Scala Question

# How to access an element of list within a list in scala

I want to access elements of a list within one list and check whether the elements are greater than a minimum value.
Example: List[([1,2],0.3), ([1.5,6],0.35), ([4,10],0.25), ([7,15],0.1)]

Let the minimum value: 1

The result should be: List[([1,6],0.65), ([4,10],0.25), ([7,15],0.1)]

As 1.5-1 is less than minimum value 1, it will merge the elements [1,2],0.3) and ([1.5,6],0.35) as [1, 6], 0.65, meaning it will take the 1st element of the inside list and last element of the 2nd element of the outside list and the 2nd element of the outside list will be added (0.3+0.35). This will be done for all elements of the outside list.
The code I tried is written below:

``````def reduce (d1:List[(Interval, Rational)]): List[(Interval, Rational)] =
{
var z = new ListBuffer[(Interval, Rational)]()
def recurse (list: List[(Interval, Rational)]): Unit = list match {
case List(x, y, _*) if ((y._1_1 - x._1_1) < min_val) =>
val i = x._1_1; y._1_2
val w = x._2 + y._2
z += (i,w)
else
z += x
recurse(list.tail)
case Nil =>
}
z.toList
}
``````

OK, what you've written really isn't Scala code, and I had to make a few modifications just to get a compilable example, but see if this works for you.

``````type Interval = (Double,Double)
type Rational = Double
def reduce (lir:List[(Interval, Rational)]): List[(Interval, Rational)] = {
val minVal = 1.0
lir.foldLeft(List.empty[(Interval, Rational)]){
case (a, b) if a.isEmpty => List(b)
case (acc, ((i2a, i2b), r2)) =>
val ((i1a, _), r1) = acc.head
if (i2a - i1a < minVal) ((i1a, i2b), r1 + r2) :: acc.tail
else ((i2a, i2b), r2) :: acc
}.reverse
}
``````

Test case:

``````reduce(List( ((1.0,2.0),0.3), ((1.5,6.0),0.35), ((4.0,10.0),0.25), ((7.0,15.0),0.1) ))
// result: List[(Interval, Rational)] = List(((1.0,6.0),0.6499999999999999), ((4.0,10.0),0.25), ((7.0,15.0),0.1))
``````