0

I have a list

what I would like to do is

def someRandomMethod(...): ... = {
  val list = List(1, 2, 3, 4, 5)
  if(list.isEmpty) return list
  list.differentScanLeft(list.head)((a, b) => {
     a * b
  })
}

which returns List(1, 2, 6, 12, 20) rather than List(1, 2, 6, 24, 120)

Is there such API?

Thank you, Cosmir

cosmir17
  • 57
  • 7

2 Answers2

0

You probably want to use zip

val list = List(1,2,3,4,5,6)
val result = list.zip(list.drop(1)).map{case (a,b) => a*b}
println(result)

> List(2, 6, 12, 20, 30)
Nazarii Bardiuk
  • 4,272
  • 1
  • 19
  • 22
  • 1
    Using `tail` is dangerous unless you know the list is not empty. Prefer `drop(1)` if there is any doubt. – Tim Sep 19 '18 at 10:00
0

scan is not really the right method for this, you want to use sliding to generate a list of adjacent pairs of values:

(1::list).sliding(2).map(l => l(0)*l(1))

More generally, it is sometimes necessary to pass data on to the next iteration when using scan. The standard solution to this is to use a tuple (state, ans) and then filter out the state with another map at the end.

Tim
  • 26,753
  • 2
  • 16
  • 29
  • selecting this answer as per it's conciseness. – cosmir17 Sep 19 '18 at 10:04
  • This solution also has the advantage that it doesn't require the list to be in a variable, it can be applied directly to the output of an earlier operation. – Tim Sep 19 '18 at 10:06