构成每个子列表的第一个元素?

时间:2018-03-30 00:06:41

标签: scheme racket

我正在编写一个函数来获取父节点的子节点,我的代码是:

(define (children elem tree)
  (if (eqv? tree '())
      '()
      (if (= elem (car tree))
          (getchilds (cdr tree))
          (children elem (cdr tree)))))

(define (getchilds childNodes)
  (cond ((null? childNodes) '())
        (else (cons (caar childNodes) (getchilds (cdr childNodes))))))

这一半起作用。 (children 10 '(10 (2 (4 (9 (3)) (12 (1 (2))) (16))) (5 (7) (21)) (6))) 输出(2 5 6)这是我所期待的

但是(children 2 '(10 (2 (4 (9 (3)) (12 (1 (2))) (16))) (5 (7) (21)) (6)))失败了。

我得到了

=: contract violation
  expected: number?
  given: (2 (4 (9 (3)) (12 (1 (2))) (16)))
  argument position: 2nd
  other arguments...:

我认为这是因为(= elem (car tree)期望一个数字作为第二个参数,但是如果我这样做的话 (car '(2 (4 (9 (3)) (12 (1 (2))) (16)))) 输出为2

所以我不太确定我的逻辑失败了。有人有个主意吗?

1 个答案:

答案 0 :(得分:2)

考虑(10 (2 (4 (9 (3)) (12 (1 (2))) (16))) (5 (7) (21)) (6))的输入列表(在您的代码中称为tree)。

当您使用(cdr tree)递归时(与(children elem (cdr tree))中一样),新的tree(在递归调用中)变为((2 (4 (9 (3)) (12 (1 (2))) (16))) (5 (7) (21)) (6))。这意味着(car tree)(2 (4 (9 (3)) (12 (1 (2))) (16))) (5 (7) (21)) (6)。那不是数字。