通过阶乘的例子,练习在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:

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



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.





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:







stack popped up:

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

Update 2016-01-11

Tail recursion implementation via Scala:

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

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月前
|
存储 JavaScript 前端开发
JS项目练习
JS项目练习
|
3月前
|
JavaScript 前端开发
记录Javascript数组类练习
记录Javascript数组类练习
19 1
|
3月前
|
JavaScript 前端开发
JS循环语句以及一些小练习
JS循环语句以及一些小练习
22 1
|
3月前
|
存储 前端开发 JavaScript
[初学者必看]JavaScript 简单实际案例练习,锻炼代码逻辑思维
【6月更文挑战第2天】这是一个前端小项目合集,包括图片轮播器、动态列表、模态框、表单验证等14个项目,旨在帮助初学者提升编码技能和实战经验。每个项目提供关键提示,如使用HTML、CSS和JavaScript实现不同功能,如事件监听、动画效果和数据处理。通过这些项目,学习者可以锻炼前端基础并增强实际操作能力。
60 2
|
3月前
|
前端开发 JavaScript 搜索推荐
[初学者必看]JavaScript 15题简单小例子练习,锻炼代码逻辑思维
【6月更文挑战第3天】这是一个JavaScript编程练习集,包含15个题目及答案:计算两数之和、判断偶数、找数组最大值、字符串反转、回文检测、斐波那契数列、数组去重、冒泡排序、阶乘计算、数组元素检查、数组求和、字符计数、数组最值和质数判断以及数组扁平化。每个题目都有相应的代码实现示例。
168 1
|
3月前
|
前端开发 JavaScript 容器
技术经验解读:个人练习:使用HTML+CSS3制作图片轮播功能(不使用JavaScript)
技术经验解读:个人练习:使用HTML+CSS3制作图片轮播功能(不使用JavaScript)
50 0
|
3月前
|
JavaScript 前端开发
记录JavaScript练习
记录JavaScript练习
17 0
|
4月前
|
JavaScript 前端开发 C语言
JavaScript编程语法练习
本篇文章是对于javaScript中if ,switch,while ,do-while,,for语法的作业练习.对于我来说也是对自己知识掌握的一种检验.是对js的基础语法进行的一次练习,通过有趣的示例进行练习,使得对于代码能够增加印象,对于知识的掌握更加透彻.
|
4月前
|
存储 JavaScript
JS中相等(==)和等全(===)的区别与练习
JS中相等(==)和等全(===)的区别与练习
35 1
|
4月前
|
移动开发 前端开发 JavaScript
H5+CSS3+JS逆向前置——4、DIV+CSS绘制旗帜练习
H5+CSS3+JS逆向前置——4、DIV+CSS绘制旗帜练习
55 0