简体   繁体   中英

Is there anything wrong with my “sum of list” code in scheme?

My else statement line is giving me an error. Is any of my other line of codes affecting the else expression?

(define (sumAdd list)
  (cond
    ((null? list) '())
    ((null? (cdr list)) list)
    ((symbol? list) sumAdd(cdr list))
    (else (+ (car list)(sumAdd (cdr list))))
    )
  )

If I understand correctly, you want to sum all the numbers in a list with mixed element types. If that's the case, there are several errors in your code:

(define (sumAdd list)                 ; `list` clashes with built-in procedure
  (cond
    ((null? list) '())                ; base case must be zero for addition
    ((null? (cdr list)) list)         ; why discard the last element?
    ((symbol? list) sumAdd(cdr list)) ; that's not how procedures are called
    (else (+ (car list) (sumAdd (cdr list)))))) ; this line is fine :)

This is the correct way to implement the procedure:

(define (sumAdd lst)
  (cond
    ((null? lst) 0)                           ; base case is zero
    ((symbol? (car lst)) (sumAdd (cdr lst)))  ; skip current element
    (else (+ (car lst) (sumAdd (cdr lst)))))) ; add current element

It works as expected:

(sumAdd '(1 a 2 b 3 c))
=> 6

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM