通过阶乘的例子,练习在JavaScript, Scala和ABAP里实现尾递归(Tail Recursion)

简介: 通过阶乘的例子,练习在JavaScript, Scala和ABAP里实现尾递归(Tail Recursion)

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


A simple factorial implementation by recursion:

function factorial(n){

 if(n ===1) {

    return 1;

 }

 return n *factorial(n -1);

}

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

image.png

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


image.png

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.

image.png

image.png

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:

function tailFactorial(n, total) {

if(n ===1)

   return total;

return tailFactorial(n -1, n * total);

}

function factorial2(n) {

 return tailFactorial(n,1);

}

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:

image.png

image.png

image.png

stack popped up:

image.png

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

image.png

Update 2016-01-11

Tail recursion implementation via Scala:


image.png

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

image.png

Tail Recursion in ABAP

First this is the normal recursion:REPORT zrecursion.

START-OF-SELECTION.

 DATA: lv_result TYPE int4.

 PERFORM fac USING 6 CHANGING lv_result.

 WRITE: / lv_result.

FORM fac USING iv_n TYPE int4 CHANGING cv_result TYPE int4.

 DATA: lv_n TYPE i.

 cv_result = lv_n = iv_n.

 lv_n = lv_n - 1.

 IF lv_n > 1.

   PERFORM fac USING lv_n CHANGING cv_result.

 ENDIF.

 IF lv_n = 1.

   cv_result = cv_result * lv_n.

 ELSE.

   cv_result = cv_result * iv_n.

 ENDIF.

ENDFORM.

And here comes tail recursion version:

REPORT ztail.

START-OF-SELECTION.

 DATA: lv_result TYPE int4.

 PERFORM fac USING 5 1 CHANGING lv_result.

 WRITE: / lv_result.

FORM fac USING iv_n TYPE int4 iv_acc TYPE int4 CHANGING cv_result TYPE int4.

 DATA: lv_n          TYPE i,

       lv_accumulate TYPE i.

 IF iv_n < 1.

   cv_result = 1.

 ELSEIF iv_n = 1.

   cv_result = iv_acc * iv_n.

 ELSEIF iv_n > 1.

   lv_n = iv_n - 1.

   lv_accumulate = iv_acc * iv_n.

   PERFORM fac USING lv_n lv_accumulate CHANGING cv_result.

 ENDIF.

ENDFORM.


相关文章
|
4月前
|
Scala
Scala综合练习_基于以下List集合实现词频统计
Scala综合练习_基于以下List集合实现词频统计
40 0
|
11月前
|
JavaScript 前端开发 API
如何使用 JavaScript 代码连接部署在 SAP ABAP 服务器上的 OData 服务试读版
如何使用 JavaScript 代码连接部署在 SAP ABAP 服务器上的 OData 服务试读版
|
JavaScript 算法 前端开发
【前端算法】JS实现数字千分位格式化
JS实现数字千分位格式化的几种思路,以及它们之间的性能比较
321 1
|
存储 前端开发 算法
一行代码解决LeetCode实现 strStr()使用JavaScript解题|前端学算法
一行代码解决LeetCode实现 strStr()使用JavaScript解题|前端学算法
152 0
一行代码解决LeetCode实现 strStr()使用JavaScript解题|前端学算法
|
存储 机器学习/深度学习 JavaScript
JS 你最少用几行代码实现深拷贝?
JS 你最少用几行代码实现深拷贝?
JS 你最少用几行代码实现深拷贝?
|
JavaScript 前端开发 算法
JavaScript实现一段时间之后关闭广告
简介:通过JavaScript实现在一段时间之后,广告消失。
117 0
JavaScript实现一段时间之后关闭广告
|
JavaScript 前端开发 算法
JS实现鼠标悬停变色
本文实现的是利用JS实现当鼠标悬停在表格上的时候,表格发生变色。 CSS渲染 JS逻辑 `
194 0
JS实现鼠标悬停变色
|
JavaScript 前端开发 数据安全/隐私保护
JS实现关闭图片窗口
通过事件的绑定来实现,关闭二维码的效果。
149 0
JS实现关闭图片窗口
|
JavaScript 前端开发
利用JavaScript实现二级联动
利用JavaScript实现二级联动 要实现JavaScript二级联动效果,首先要确定需要哪些技术: 二维数组 for in循环 new Option(text,value,true,true) add(option,null) onchange() 表单事件 HTML代码: &lt;!-- &lt;input type=&quot;text&quot; id=&quot;text&quot;&gt; --&gt; 请选择省份: &lt;select name=&quot;&quot; id=&quot;provinces&quot;&gt; &lt;!-- &lt;option value=&quot;江苏省&quot;&gt;江苏省&lt;/option&gt;
|
JavaScript 前端开发
JavaScript函数柯里化的实现原理,进来教你完成一个自己的自动实现柯里化方法
JavaScript函数柯里化的实现原理,进来教你完成一个自己的自动实现柯里化方法
183 0