Scheme在列表的列表中添加奇数元素



我试图在列表中添加我列表中的所有奇数原子,以便获得每个奇数原子并将它们添加在一起。我得到一个错误说:

+:违反合同预期:号码吗?鉴于:()

所以我假设我要到列表的末尾,并在添加时抛出空列表?但我不确定如何解决这个问题或绕过这个问题。


(define (sumodd list)
(cond ((null? list) 0)

((list? (car list)) (sumodd (cdr list)))
((odd? (car list))
(+ (car list) (sumodd (cdr list))))
(sumodd (cdr list))

))
(sumodd '(1 (2 () 6) 3 (5) 8))

首先,不要使用符号list作为变量名。list的值为#<procedure:list>,当您重写此值时,将无法使用该函数。看到的例子:

(define (testlist list)
(list list))
(testlist (list 1 2 3))

你的解决方案有两个错误:

  1. (list? (car lst))时,必须将(car lst)(cdr lst)相加。
  2. cond的最后一个分支中缺少else子句

解决方案:

(define (sumodd lst)
(cond ((null? lst) 0)        
((list? (car lst)) (+ (sumodd (car lst))
(sumodd (cdr lst))))
((odd? (car lst)) (+ (car lst)
(sumodd (cdr lst))))
(else (sumodd (cdr lst)))))
(sumodd '(1 (2 () 6) 3 (5) 8))

这个结果也可以通过:

(require racket/list)
(define (sumodd2 lst)
(apply + (filter odd? (flatten lst))))
(sumodd2 '(1 (2 () 6) 3 (5) 8))

最新更新