天天看點

JavaScript和ABAP的尾遞歸

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

A simple factorial implementation by recursion:​

JavaScript和ABAP的尾遞歸

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

JavaScript和ABAP的尾遞歸

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

JavaScript和ABAP的尾遞歸
JavaScript和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和ABAP的尾遞歸
JavaScript和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.

tail recursion

Source code below:

JavaScript和ABAP的尾遞歸

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和ABAP的尾遞歸
JavaScript和ABAP的尾遞歸
JavaScript和ABAP的尾遞歸

stack popped up:

JavaScript和ABAP的尾遞歸

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

JavaScript和ABAP的尾遞歸

Update 2016-01-11

Tail recursion implementation via Scala:

JavaScript和ABAP的尾遞歸

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

JavaScript和ABAP的尾遞歸

Tail Recursion in ABAP

First this is the normal recursion:

JavaScript和ABAP的尾遞歸

And here comes tail recursion version:

JavaScript和ABAP的尾遞歸