Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
299 views
in Technique[技术] by (71.8m points)

scala - How immediatly return accumulator from foldLeft


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...