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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With