how to check if a number is power of two in Scheme by tail recursion?
(define (ispowerof2? n)开发者_JAVA百科
(cond ((< n 1) #f)
((= n 1) #t)
((> (remainder n 2) 0) #f)
(else (ispowerof2? (/ n 2)))))
Is this code correct and how to write the same function with tail recursion?
I agree with the other two answers. To explain a bit more deeply: a "tail-recursive" function is one where all recursive calls are in tail position. This begs the question of what constitutes a tail call.
One way to see the tail calls is to run this function using DrRacket's stepper. In particular, set the langage level to "Beginning Student" and click the "step" button on this program:
(define (ispowerof2? n)
(cond
((< n 1) false)
((= n 1) true)
((> (remainder n 2) 0) false)
(else (ispowerof2? (/ n 2)))))
(ispowerof2? 36)
... then step forward until you get to a recursive call:
(define (ispowerof2? n)
(cond
((< n 1) false)
((= n 1) true)
((> (remainder n 2) 0) false)
(else (ispowerof2? (/ n 2)))))
(ispowerof2? (/ 36 2))
Note that the recursive call is at the top level; there's no "context" wrapping it, with code to be applied to the result of the call. This is what is meant by a "tail call". Contrast this with a function that computes the length of a list:
(define (len l)
(cond
((empty? l) 0)
(else (+ 1 (len (rest l))))))
(len (cons 3 (cons 4 empty))
Step forward until you get a recursive call, and you'll see this:
(define (len l)
(cond
((empty? l) 0)
(else (+ 1 (len (rest l))))))
(+ 1 (len (list 4)))
See how the recursive call to 'len' is inside of a (+ 1 ...) expression? That's because this call is not in tail position; there are still more expressions to evaluate in this function after the return of the recursive call.
Not quite. The line:
(else (ispower2? (/ n 2)))))
Contains an error - it should be ispowerof2
. Otherwise, this is tail recursion.
Yes, this is tail recursive. :)
精彩评论