简体   繁体   中英

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”. 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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