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
338 views
in Technique[技术] by (71.8m points)

recursion - Is there a way to optimize tail calls in Scala?

I am aware that Scala has optimizations for tail-recursive functions (i.e. those functions in which the recursive call is the last thing executed by the function). What I am asking here is whether there is a way to optimize tail calls to different functions. Consider the following Scala code:

def doA(): Unit = {
  doB()
}

def doB(): Unit = {
  doA()
}

If we let this execute long enough it will give a stack overflow error which one can mitigate by allocating more stack space. Nonetheless, it will eventually exceed the allocated space and once again cause a stack overflow error. One way to mitigate this could be:

case class C(f: () => C)

def run(): Unit = {
  var c: C = C(() => doA())
  while(true){
    c = c.f.apply()
  }
}

def doA(): C = {
  C(() => doB())
}

def doB(): C = {
  C(() => doA())
}

However, this proved to be quite slow. Is there a better way to optimize this?

question from:https://stackoverflow.com/questions/65868273/is-there-a-way-to-optimize-tail-calls-in-scala

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

1 Reply

0 votes
by (71.8m points)

Here's one way achieve an infinite progression of method calls, without consuming stack, where each method decides which method goes next.

def doA(): () => Any = {
  doB _
}
def doB(): () => Any = {
  doC _
}
def doC(): () => Any = {
  if (util.Random.nextBoolean()) doA _
  else                           doB _
}

Iterator.iterate(doA())(_.asInstanceOf[() => () => Any]())
        .foreach(identity)

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

...