learning scala Function Recursive Tail Call

可以使用scala库,可以从字面上看出是在调用 递归函数:

code

import scala.util.control.TailCalls._

  val arrayDonuts: Array[String] = Array("Vanilla Donut", "Strawberry Donut", "Plain Donut", "Glazed Donut")

  println("\nStep : How to define a tail recursive function using scala.util.control.TailCalls._")
def tailSearch(donutName: String, donuts: Array[String], index: Int): TailRec[Option[Boolean]] = {
if(donuts.length == index) {
done(None) // NOTE: done is imported from scala.util.control.TailCalls._
} else if(donuts(index) == donutName) {
done(Some(true))
} else {
val nextIndex = index +
tailcall(tailSearch(donutName, donuts, nextIndex)) // NOTE: tailcall is imported from scala.util.control.TailCalls._
}
} println("\nStep : How to call tail recursive function using scala.util.control.TailCalls._")
val tailFound = tailcall(tailSearch("Glazed Donut", arrayDonuts, ))
println(s"Find Glazed Donut using TailCall = ${tailFound.result}") // NOTE: our returned value is wrapped so we need to get it by calling result val tailNotFound = tailcall(tailSearch("Chocolate Donut", arrayDonuts, ))
println(s"Find Chocolate Donut using TailCall = ${tailNotFound.result}")

resule:

Step : How to define a tail recursive function using scala.util.control.TailCalls._

Step : How to call tail recursive function using scala.util.control.TailCalls._
Find Glazed Donut using TailCall = Some(true)
Find Chocolate Donut using TailCall = None

  

上一篇:Scala Control Structures


下一篇:[Java] JVM 在执行 main 方法前的行为