从列表中挑选7。

时间:2013-02-28 14:42:31

标签: scheme racket

我正试图从列表中选出7,这是我的代码:

(define (pick7 x)
  (cond ((null? x) x)
        ((= (car x) 7) pick7 (cdr x))
        (else (cons (car x) (pick7 (cdr x))))))

但是当我拨打(pick7 (1 3 (5 7) 9))时,它会给我一个错误。我想我看到了问题 - (car x)并不总是一个数字,所以我需要将其分解。

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:3)

如果通过“挑选”意味着从列表中“删除”一个元素,这里是你如何为任意嵌套列表列表,填写空白:

(define (pick7 x)
  (cond (<???> <???>)               ; if the list is null, return null
        ((not (pair? <???>))        ; if the first element is not a list
         (if <???>                  ;   if the first element is 7
             (pick7 <???>)          ;   advance recursion over rest of list
             (cons <???>            ;   else cons the first element and
                   (pick7 <???>)))) ;   advance recursion over rest of list
        (else (cons                 ; if the first element is a list, then cons
               (pick7 <???>)        ; the recursion over the first element
               (pick7 <???>)))))    ; and the recursion over the rest of list

请注意,这是处理任意嵌套列表列表的标准模板,适用于以下情况:

(pick7 '(1 3 (5 7 (8 7 (10 7 11))) 9 7))
=> '(1 3 (5 (8 (10 11))) 9)

答案 1 :(得分:2)

从列表中选出7是什么意思?你的意思是删除它?如果是这样,您还需要检查第一个元素是否为列表。

(define (pick7 x)
  (cond ((null? x) x)
        ((<??>) (cons (pick7 (car x)) (pick7 (cdr x))))
        ((= (car x) 7) (pick7 (cdr x)) ; missing paren
        (else (cons (car x) (pick7 (cdr x))))))