可以使用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 + 1 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, 0)) 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, 0)) 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