Search code examples
sumlispnested-lists

Sum of numeric elements in a nested list LISP


Return the SUM of numeric elements in a nested list using LISP. If there are no numeric elements return an empty list/NIL

Examples:

         (6 3 -2 5 (4 2 -3) 4) should return 19
     

         (1 2 3 (-4 5) a b c) should return 7

Solution

  • Asking other people to do your homework for you is almost never a good way of learning anything.

    But here's an answer, which is written in a Lisp (Racket) and which does show how you ought to go about solving this problem, and also (I think) demonstrates some nice ways of thinking about problems like this ... but which you almost certainly can't cut and paste.

    Note that this does not quite agree with the requirements given: which is supposed to return a non-numeric value for a list with no numbers in it. That breaks a recursive algorithm like this, since the empty list is a list with no numbers in it. So this does something more sensible. Making this answer implement the requirements is left as an exercise to the student.

    (define (sum-nested-list l)
      (let sum-nested-list-loop ([thing l]
                                 [running-total 0])
        (match thing
          ['()
           ;; We're done if we've run out of list
           running-total]
          [(list* (? number? x) r)
           ;; A list whose first element is a number: add it to the running total
           ;; and carry on on the rest of the list
           (sum-nested-list-loop r (+ running-total x))]
          [(list* (? list? x) r)
           ;; A list whose first element is a nested list: recurse into the
           ;; nested list
           (sum-nested-list-loop r (sum-nested-list-loop x running-total))]
          [(list* _ r)
           ;; A list whose first element is not a number or a nested list:
           ;; carry on on the rest of the list
           (sum-nested-list-loop r running-total)]
          [_
           ;; Not a list at all: explode
           (error 'sum-numeric-list "what?")])))