Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala map list element to a value calculated from previous elements

I have a list of string elements in Scala:

val list = List("a", "b", "c")

Is there any concise way to construct another list, in which each i-th element will be constructed from 0..i-th elements of list (in my case it is list.take(i + 1).mkString("|") )

val calculatedLst = briefFunc(list) // List("a", "a|b", "a|b|c")
like image 455
pavel_kazlou Avatar asked Dec 12 '22 01:12

pavel_kazlou


1 Answers

What you are looking for is scan, which accumulates a collection of intermediate cumulative results using a start value.

Very quick try with scanLeft. Will fail if the list is empty.

val list = List("a", "b", "c")                   
list.drop(1).scanLeft(list.head) {
  case (r, c) => r + "|" + c
}                                              
//> res0: List[String] = List(a, a|b, a|b|c)
like image 58
mohit Avatar answered Apr 20 '23 00:04

mohit