GDT GDT - 17 days ago 7
Scala Question

How to break early when foldLeft over simple List?

This is a simplified version of my problem, I want to stop the fold return the value after the if condition is met in the fold where a.size == 7.

class test1 {

def test(a : List[Int]): Int = {
val list = a.foldLeft(if(a.size == 7) 1000 else 0)((b,a) => a + b )

list
}
}



object test1 extends App{
val temp1 = new test1()

val list: List[Int] = List(1,2,3,4,5,6,7)

println(temp1.test(list))


}


As you can see the condition is met on the first fold, but there are cases where it can be met on the second or first. Not sure where to go from here any help with be appreciated

Answer

Try next template:

def Process(A: List[Int]) : Int = {

  def proces(a: List[Int], acc: List[Int]): Int = a match {
    case List () => -1
    case h :: tail => if (acc.length == 10) 1000 else proces (tail, h :: acc)
  }
  proces(A, List() )
}