Home > Net >  Lisp - recursive function add numbers form list
Lisp - recursive function add numbers form list

Time:11-26

Could someone help me with the following task? Unfortunately, I find it too complicated.

Write a recursive function ADD that takes a list as a parameter and adds all the numbers from the list together, sums up the result and outputs it. The function should be defined so that the passed list can also contain symbols and strings.

This is the function I wrote:

(defun add (l)
  (cond
   ((null l) nil)
   ((not (numberp (first l))) nil) (add (rest l))
   ((numberp (first l) (  (first l) (add (rest l)))))
   (t (  (add (first l) (add (rest l)))))))`

CodePudding user response:

That seems like a genuine effort (but next time, you can add your code to your question and don't create a new answer), so here you are:

This problem is a combination of some basic recursive patterns- it would help you to start with a recursive sum of a non-nested list:

(defun add (l)
  (if (null l) 0
    (  (first l) (add (rest l)))))

Then a recursive sum with skipping non-numbers:

(defun add (l)
  (cond ((null l) 0)
        ((numberp (first l))
         (  (first l)
            (add (rest l))))
        (t (add (rest l)))))

Sum of a nested list:

(defun add (l)
  (cond ((null l) 0)
        ((listp (first l))
         (  (add (first l))
            (add (rest l))))
        (t (  (first l)
              (add (rest l))))))

And finally, a sum of a nested list with skipping non-numbers:

(defun add (l)
  (cond ((null l) 0)
        ((listp (first l))
         (  (add (first l))
            (add (rest l))))
        ((numberp (first l))
         (  (first l)
            (add (rest l))))
        (t (add (rest l)))))

Some tests:

> (add '(1 2 3 4 5 "foo" 6))
21

> (add '("bar" 1 2 3 4 5 "foo" 6 'y))
21

> (add '((1 2 (3))))
6

CodePudding user response:

That's my try:

(defun add (l)
  (cond
   ((null l) nil)
   ((not (numberp (first l))) nil) (add (rest l))
   ((numberp (first l) (  (first l) (add (rest l)))))
   (t (  (add (first l) (add (rest l)))))))`
  • Related