scalalistimmutablelist

In Scala, is it possible to use fold left to do summation up to certain index in the list?


I am trying to find an effective way to do summation of the list up to the selected index.

var groupList : List[Int] = List(1,3,4,5)

What can i do to achieve if i select indexOf(2), it will do summation up to that index? ( 1 + 3 + 4) ?


Solution

  • How about:

    val idx = 2
    groupList.take(idx+1).sum
    // res3: Int = 8
    

    Or for efficiency:

    groupList.toIterator.take(idx+1)
    // res4: Iterator[Int] = non-empty iterator
    
    groupList.toIterator.take(idx+1).sum
    // res5: Int = 8