简体   繁体   English

这个Scheme函数尾递归吗?

[英]Is this Scheme function tail recursive?

The function receives a number and returns the number of bits that would have been required to be “on” in order to represent the input number in binary base. 该函数接收一个数字并返回为了表示二进制基数中的输入数而需要“打开”的位数。 For example, the number 5 is represented as 101 in binary and therefore requires two bits to be “on”. 例如,数字5以二进制表示为101,因此需要两个比特为“开”。 I need to know if the function I wrote is tail recursion. 我需要知道我写的函数是否是尾递归。 If not, how can I turn it to tail recursion? 如果没有,我怎么能把它变成尾递归? Thanks! 谢谢!

My function: 我的功能:

(define (numOfBitsOn number)
  (define (numOfBitsOn-2 number acc)
      (if (> number 0)
           (if (odd? number)
               (numOfBitsOn-2(/(- number 1) 2) (+ acc (modulo number 2)))
               (numOfBitsOn-2 (/ number 2) acc))
           acc))
  (numOfBitsOn-2 number 0))

DrRacket can help you determine whether a call is in tail position or not. DrRacket可以帮助您确定呼叫是否处于尾部位置。 Click the "Syntax Check" button. 单击“语法检查”按钮。 Then move the mouse pointer to the left parenthesis of the expression in question. 然后将鼠标指针移动到相关表达式的左括号。 In an example I get this: 在一个例子中,我得到了这个:

TCO示例

The purple arrow shows that the expression is in tail-position. 紫色箭头表示表达式处于尾部位置。

From the manual: 从手册:

Tail Calls: Any sub-expression that is (syntactically) in tail-position with respect to its enclosing context is annotated by drawing a light purple arrow from the tail expression to its surrounding expression. 尾调用:通过从尾表达式到其周围表达式绘制浅紫色箭头来注释(语法上)相对于其封闭上下文在尾部位置的任何子表达式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM