The following LISP function sum adds up the values in an int
The following LISP function \'sum\' adds up the values in an integer list. (defun sum (L) cond ((null L) 0) (t (+ (car L) (sum (cdr L)))))) Some outputs are given below, > (sum \'(1 2 3)) 6 > (sum \'(12 345)) 15 > (sum \'()) 0 > Write an equivalent LISP function in tail-recursive form. (No \'setq\' allowed)
Solution
(defun tailrecsum (L sum)
cond ((null L) sum)
(t (tailrecsum((cdr L) (+ (car L) sum)))))
This above code will call itself tail recursively and return the sum of list elements
in this two parameters are passing a list and a sum which is 0
then it will sum the first element of list with sum the call itself again with a list having the first element removed and the sum till now
output:
>(tailrecsum \'(1 2 3) 0)
>6
if you struck somewhere please comment!!
Good Luck!!
