如何在JavaScript, Scala和ABAP里实现尾递(abap,javascript,scala,web开发)

时间:2024-05-07 22:52:43 作者 : 石家庄SEO 分类 : web开发
  • TAG :

    %E5%A6%82%E4%BD%95%E5%9C%A8JavaScript%2C+Scala%E5%92%8CABAP%E9%87%8C%E5%AE%9E%E7%8E%B0%E5%B0%BE%E9%80%92

Before we start to research tail recursion, let’s first have a look at the normal recursion.

A simple factorial implementation by recursion:

Let N = 5, see how new stack frame is created for each time of recursive call:

如何在JavaScript, Scala和ABAP里实现尾递

We have two stack frames now, one stores the context when n = 5, and the topmost one for current calculation: n = 4

如何在JavaScript, Scala和ABAP里实现尾递

如何在JavaScript, Scala和ABAP里实现尾递

如何在JavaScript, Scala和ABAP里实现尾递

Now since n equals to 1, we stop recursion. The current stack frame ( n = 1 ) will be poped up, the frame under it will be activated and become the topmost frame, with calculated result 1 passed into.

如何在JavaScript, Scala和ABAP里实现尾递

如何在JavaScript, Scala和ABAP里实现尾递

如何在JavaScript, Scala和ABAP里实现尾递

如何在JavaScript, Scala和ABAP里实现尾递

如何在JavaScript, Scala和ABAP里实现尾递

key note for normal recursion: during recursion, every generated stack frame is needed and could not e destroyed until the final result is calculated. The calculation is actually not started until the recursion reaches the end ( the condition n === 1 fulfills ). If N is a big integer, it will lead to huge number of stack frames and finally the “stack overflow” or “out of memory” is inevitable.

Source code below:

There are two biggest differences compared with normal recursion:

(1) A new internal function tailFactorial is introduced here.

(2) The calculation is actually now spread within every recursive stack frame. Each frame finishes one part of calculation and pass the current result to the next frame. Once the current stack frame finishes its task, it is actually not needed any more. And thus for example the model browser can then do some optimization on those useless stack frames.

Observe the stack frame for tail recursion step by step:

如何在JavaScript, Scala和ABAP里实现尾递

如何在JavaScript, Scala和ABAP里实现尾递

如何在JavaScript, Scala和ABAP里实现尾递

如何在JavaScript, Scala和ABAP里实现尾递

如何在JavaScript, Scala和ABAP里实现尾递

如何在JavaScript, Scala和ABAP里实现尾递

如何在JavaScript, Scala和ABAP里实现尾递

stack popped up:

如何在JavaScript, Scala和ABAP里实现尾递

When N = 20, the tail recursion has a far better performance than the normal recursion:

如何在JavaScript, Scala和ABAP里实现尾递

Tail recursion implementation via Scala:

如何在JavaScript, Scala和ABAP里实现尾递

The interesting thing is, after the Scala code is compiled into Java Byte code, compiler will eliminate the recursion automatically:

如何在JavaScript, Scala和ABAP里实现尾递

First this is the normal recursion:

And here comes tail recursion version:

本文:如何在JavaScript, Scala和ABAP里实现尾递的详细内容,希望对您有所帮助,信息来源于网络。
上一篇:web前端学习路线-20个真实web开发项目集合下一篇:

14 人围观 / 0 条评论 ↓快速评论↓

(必须)

(必须,保密)

阿狸1 阿狸2 阿狸3 阿狸4 阿狸5 阿狸6 阿狸7 阿狸8 阿狸9 阿狸10 阿狸11 阿狸12 阿狸13 阿狸14 阿狸15 阿狸16 阿狸17 阿狸18