Can anyone help me with this please?
(define f (lambda (x)
(cond
((null? x) 0)
(#t (+ (* (car x) (car x)) (f (cdr x)))))))
I couldn't understand if this function is tail recursive or not? If it is, what is the reason?
Can anyone help me with this please?
(define f (lambda (x)
(cond
((null? x) 0)
(#t (+ (* (car x) (car x)) (f (cdr x)))))))
I couldn't understand if this function is tail recursive or not? If it is, what is the reason?
It's not tail recursive because the last thing the function does before returning is to evaluate (+ ...)
. In order to be tail recursive the last operation before returning has to be the recursive call.
Making a function tail recursive usually involves a helper function which takes an accumulator parameter:
(define f0 (lambda (x acc)
(if (null? x)
acc
(f0 (cdr x) (+ acc (* (car x)(car x)))))))
(define f (lambda (x)
(f0 x 0)))