简体   繁体   English

方案中的“列表总数”代码有什么问题吗?

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

My else statement line is giving me an error. 我的else语句行给我一个错误。 Is any of my other line of codes affecting the else expression? 我的其他任何代码行是否会影响else表达式?

(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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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