【问题标题】:Recursively processing a nested list in scheme to search for an atom递归处理方案中的嵌套列表以搜索原子
【发布时间】:2017-01-19 09:07:18
【问题描述】:

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

(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 递归搜索它。

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

【问题讨论】:

  • 你忘了问一个问题,但我猜你有一个“不是程序”的问题?
  • 对不起!是的,那是我的问题。

标签: list recursion scheme


【解决方案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))))))

【讨论】:

  • 啊,非常感谢!我很高兴看到我离得不远,而且这个修复似乎正在奏效。展平这两个条件确实有助于提高可读性!此外,我还仔细阅读了我的代码,但我仍然无法捕捉到那个参数错误,所以也谢谢你!
猜你喜欢
  • 1970-01-01
  • 2014-03-06
  • 2017-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-18
  • 2018-07-19
  • 1970-01-01
相关资源
最近更新 更多