递归处理方案中的嵌套列表以搜索原子

时间:2016-09-11 23:33:40

标签: list recursion scheme

我的目标是递归遍历任何给定的列表并计算给定原子在列表中出现的次数。我一直收到涉及程序的错误。目前我的代码如下所示:

(define (count atom x)
(cond
    ((null? x) 0)
    ((not (list? (car x)))
        (cond
            ((eqv? (car x) atom) (+ 1 (count(atom (cdr x)))))
            (else(+ 0 (count atom (cdr x))))))
    (else(+ (count atom (cdr x)) (count atom (car x))))))

(display(count 1 '(1 3)))

我尝试使用car检查第一个元素是否不是嵌套列表。如果不是,我将它与原子进行比较。如果它等于原子,我递归,向返回值加1,否则我在加0时递归。如果列表的第一个元素确实是嵌套列表,那么我使用cdr和car递归搜索它。

为了使我的问题更清楚,为什么我会收到此程序错误?我接近最终解决方案吗?

1 个答案:

答案 0 :(得分:1)

看着你的cond,你可以通过切换最后两个来将这两个变为一个:

(define (count atom x)
  (cond
    ((null? x) 0)
    ((list? (car x)) (+ (count atom (cdr x)) (count atom (car x))))
    ((eqv? (car x) atom) (+ 1 (count (atom (cdr x)))))
    (else (+ 0 (count atom (cdr x))))))

在倒数第二个学期中,你试图将你的元素称为过程(atom (cdr x)),它是count的一个参数,它需要两个。删除额外的括号我找不到任何问题:

(define (count atom x)
  (cond
    ((null? x) 0)
    ((list? (car x)) (+ (count atom (cdr x)) (count atom (car x))))
    ((eqv? (car x) atom) (+ 1 (count atom (cdr x)))) ; changes this
    (else (+ 0 (count atom (cdr x))))))