Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scheme sum of list

First off, this is homework, but I am simply looking for a hint or pseudocode on how to do this.

I need to sum all the items in the list, using recursion. However, it needs to return the empty set if it encounters something in the list that is not a number. Here is my attempt:

(DEFINE sum-list
  (LAMBDA (lst)
    (IF (OR (NULL? lst) (NOT (NUMBER? (CAR lst))))
      '()
      (+
        (CAR lst)
        (sum-list (CDR lst))
      )
    )
  )
)

This fails because it can't add the empty set to something else. Normally I would just return 0 if its not a number and keep processing the list.

like image 681
rem45acp Avatar asked Dec 18 '25 23:12

rem45acp


2 Answers

I suggest you use and return an accumulator for storing the sum; if you find a non-number while traversing the list you can return the empty list immediately, otherwise the recursion continues until the list is exhausted.

Something along these lines (fill in the blanks!):

(define sum-list
  (lambda (lst acc)
    (cond ((null? lst) ???)
          ((not (number? (car lst))) ???)
          (else (sum-list (cdr lst) ???)))))

(sum-list '(1 2 3 4 5) 0)
> 15

(sum-list '(1 2 x 4 5) 0)
> ()
like image 123
Óscar López Avatar answered Dec 21 '25 20:12

Óscar López


I'd go for this:

(define (mysum lst)
  (let loop ((lst lst) (accum 0))
    (cond
      ((empty? lst) accum)
      ((not (number? (car lst))) '())
      (else (loop (cdr lst) (+ accum (car lst)))))))
like image 43
uselpa Avatar answered Dec 21 '25 20:12

uselpa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!