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

时间:2019-02-06 23:47:13

标签: scheme

我的else语句行给我一个错误。我的其他任何代码行是否会影响else表达式?

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

1 个答案:

答案 0 :(得分:2)

如果我理解正确,您想将元素混合类型的列表中的所有数字相加。在这种情况下,您的代码中有几个错误:

(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 :)

这是实现该过程的正确方法:

(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

它按预期工作:

(sumAdd '(1 a 2 b 3 c))
=> 6
相关问题