Naseebullah Safi - 1 year ago 74
Scala Question

# How to get the current and next element of List of list of options in scala

This question might be duplicated, however, I've not come across any question that answers my problem.

So I have a

`List[ List[ Option[ Double ] ] ]`

With the following data:

``````var tests = List(
List(Some(313.062468), Some(27.847252)),
List(Some(301.873641), Some(42.884065)),
List(Some(332.373186), Some(53.509768))
)
``````

I'd like to calculate this equation:

``````def findDifference(oldPrice: Option[Double], newPrice: Option[Double]): Option[Double] = {
return Some(( newPrice.get - oldPrice.get ) / oldPrice.get)
}
``````

on the following:

It's doing the calculation on the element of two lists:

`(Some(301.062468) - Some(313.062468)) / Some(313.062468)`

`(Some(332.373186) - Some(301.873641)) / Some(301.873641)`

`(Some(42.884065) - Some(27.847252)) / Some(27.847252)`

`(Some(53.509768) - Some(42.884065)) / Some(42.884065)`

The result should return:
#

``````List(
List(Some(-0.03573991820699504), Some(0.5399747522663995))
List(Some(0.10103414428290529), Some(0.24777742035415723))
)
``````

# My code so far

``````def findDifference(oldPrice: Option[Double], newPrice: Option[Double]): Option[Double] = {
return Some(( newPrice.get - oldPrice.get ) / oldPrice.get)
}

def get_deltas(data: List[List[Option[Double]]]):  List[List[Option[Double]]] = {
for {
i <- data
// So this is where I am stuck. I have the current element i, but I need the same index element in the next list
} ( findDifference(i,?) }
``````

# My output If I print my I in For-comprehension

``````List(Some(313.062468), Some(27.847252))
List(Some(301.873641), Some(42.884065))
List(Some(332.373186), Some(53.509768))``````

# Where Am I stuck?

I'm stuck in the fact that I don't know how to get the element of the same index in the list 1 from List 2 and List 3 and do the necessary calculation?

Try to play with this:

``````object OptIdx {

def main(args: Array[String]) {
println(get_deltas(tests))
}

var tests = List(
List(Some(313.062468), Some(27.847252)),
List(Some(301.873641), Some(42.884065)),
List(Some(332.373186), Some(53.509768)))

def findDifference(oldPrice: Option[Double], newPrice: Option[Double]): Option[Double] = {
Some((newPrice.get - oldPrice.get) / oldPrice.get)
}

def get_deltas(data: List[List[Option[Double]]]): List[List[Option[Double]]] = {
(for {
index <- 0 to 1
} yield {
(for {
i <- 0 to data.length - 2
} yield {
findDifference(data(i)(index), data(i + 1)(index))
}).toList
}).toList
}

}
``````

It prints the numbers you want, but two of them are swapped. I'm sure you can figure it out, though.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download