2

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

Gioan Nguyen
  • 37
  • 10
  • you will have to implement your own recursive folderLeft and process list under your conditions – Pavel Nov 23 '16 at 19:45
  • Hey @PavelOliynyk, I am not sure what you mean here can you show me? – Gioan Nguyen Nov 23 '16 at 19:49
  • @PavelOliynyk How do i use the function , it wants two lists but i have one :> sorry im still a novice – Gioan Nguyen Nov 23 '16 at 19:57
  • Answer updated. Don't forget to accept answer !:)) Simple use of local lexical scope. – Pavel Nov 23 '16 at 20:00
  • 2
    A more complete set of answers can be found [here](http://stackoverflow.com/questions/12892701/abort-early-in-a-fold). – jwvh Nov 23 '16 at 20:12
  • Does this answer your question? [Abort early in a fold](https://stackoverflow.com/questions/12892701/abort-early-in-a-fold) – pme Jan 14 '20 at 12:32

1 Answers1

3

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() )
}
Pavel
  • 1,519
  • 21
  • 29