You can consider using @tailrec
instead of foldLeft
:
import scala.annotation.tailrec
@tailrec
def methodOption1(values: List[Int])(acc: Int): Int = {
if(acc > 5 || values.isEmpty) acc
else method(values.tail)(acc + values.head)
}
@tailrec
def methodOption2(values: List[Int])(sum: Int): Int = {
values match {
case Nil => sum
case _ if sum > 5 => sum
case e :: tail => method(tail)(sum + e)
}
}
methodOption1(List(1, 2, 3, 4, 5))(0)
methodOption2(List(1, 2, 3, 4, 5))(0)
You also can make Mapper to "view" it as .foldLeft
implicit class ListMapper[A](xs: List[A]) {
def foldLeftAsTailRecWithStop[B](z: B)(op: (B, A) => B)(stop: B => Boolean): B = {
@tailrec
def tailrec(xs: List[A])(acc: B): B = {
if(xs.isEmpty || stop(acc)) acc
else tailrec(xs.tail)(op(acc, xs.head))
}
tailrec(xs)(z)
}
def foldLeftAsTailRec[B](z: B)(op: (B, A) => B): B = {
@tailrec
def tailrec(xs: List[A])(acc: B): B = {
if(xs.isEmpty) acc
else tailrec(xs.tail)(op(acc, xs.head))
}
tailrec(xs)(z)
}
}
List(1, 2, 3,4,5).foldLeft(0)(_ + _)
List(1, 2, 3,4,5).foldLeftAsTailRec(0)(_ + _)
List(1, 2, 3,4,5).foldLeftAsTailRecWithStop(0)(_ + _)(_ > 5)
Outputs:
res0: Int = 15
res1: Int = 15
res2: Int = 6
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…