GDT GDT - 1 year ago 101
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 )


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

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



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 Source

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() )
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download