Search code examples
scalafunctional-programming

How to pass the initial value to foldLeft from a filtered List with function chaining?


Say I have a List. I filter it first on some condition. Now I want to pass the initial value from this filtered array to foldLeft all while chaining both together. Is there a way to do that?

For example:

scala> val numbers = List(5, 4, 8, 6, 2)
val numbers: List[Int] = List(5, 4, 8, 6, 2)

scala> numbers.filter(_ % 2 == 0).foldLeft(numbers(0)) { // this is obviously incorrect since numbers(0) is the value at index 0 of the original array not the filtered array
     |   (z, i) => z + i
     | }
val res88: Int = 25

Solution

  • You could just pattern match on the result of filtering to get the first element of list (head) and the rest (tail):

    val numbers = List(5, 4, 8, 6, 2)
    
    val result = numbers.filter(_ % 2 == 0) match {
      case head :: tail => tail.foldLeft(head) {
            (z, i) => z + i
      }
       // here you need to handle the case, when after filtering there are no elements, in this case, I just return 0
      case Nil => 0
    }
    

    You could also just use reduce:

    numbers.filter(_ % 100 == 0).reduce {
       (z, i) => z + i
    }
    

    but it will throw an exception in case after filtering the list is empty.