BigMeister
BigMeister

Reputation: 371

Is the named let tail recursive?

These two examples do the factorial of a number:

(define (factorial n)
  (define (execute n result)
    (cond
         [(> 2 n) result]
         [else (execute (- n 1) (* result n))]))
  (execute n 1))

And

(define (factorial n)
  (let loop ((curr n)
             (result 1))
    (cond
         [(> 2 curr) result]
         [else (loop (- curr 1) (* result curr))])))

The difference reside in using the named-let. Are they both pure and tail recursive functions?

Upvotes: 0

Views: 259

Answers (1)

Barmar
Barmar

Reputation: 780723

Yes, they are tail-recursive, and they're essentially equivalent.

A named let is just a shorthand for a function definition along with a first call using the initial values as the arguments.

A function is tail-recursive if all its calls to itself are in tail positions, i.e. it simply returns the value of that call. In the first function, the recursive call to execute is in the tail position; in the second function the same is true of the call to loop.

Upvotes: 2

Related Questions