简体   繁体   中英

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")

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM