我正在尝试从列表中选择 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)
并不总是一个数字,所以我需要分解它。
我该如何解决?
如果通过“挑选”您的意思是从列表中“删除”一个元素,那么对于任意嵌套列表的列表,您会这样做,请填写空白:
(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)
从列表中选择 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))))))