1

我需要从列表中完全删除给定的数字。这将被输入: (remove-digit 1 '(1 2 3 '(4556 1)))

我需要返回(2 3 (4556)) 我可以使用以下代码从列表中删除:

(define (remove-digit digit list)
  (cond ((null? list) list)
        ((= digit (car list)) (remove-digit digit (cdr list)))
        (else (cons (car list) (remove-digit digit (cdr list))))))

但不能从列表中的列表中删除。非常感谢任何帮助

4

3 回答 3

2

您需要在cond语句中添加一个子句,处理(子)列表:

(define (remove-digit digit list)
  (cond ((null? list) list)
        ((eqv? digit (car list)) (remove-digit digit (cdr list)))
        ((list? (car list)) (cons (remove-digit digit (car list)) 
                                  (remove-digit digit (cdr list))))
        (else (cons (car list) (remove-digit digit (cdr list))))))
于 2013-04-28T19:44:07.457 回答
0
(define (rem-dig n ds)
  (cond
    ((list? ds) 
       (remove-digit n (map (lambda(d)(rem-dig n d)) ds)))
    (else ds)))

需要将等式谓词从 number-specific 替换为=general equal?

(define (remove-digit digit list)
  (cond ((null? list) list)
        ((equal? digit (car list)) (remove-digit digit (cdr list)))
        (else (cons (car list) (remove-digit digit (cdr list))))))

测试:

(rem-dig 1 '(1 2 3 (4556 1)))
;Value 13: (2 3 (4556))

如果允许不正确的点列表,则应对其进行调整,

(define (rem-dig n ds)
  (cond
    ((list? ds) 
       (remove-digit n (map (lambda(d)(rem-dig n d)) ds)))
    ((pair? ds)
       (let* ((x  (last-pair ds))
              (y  (cdr x))
              (z  (set-cdr! x ()))
              (ds (rem-dig n ds))
              (x  (last-pair ds)))
         (if (not (equal? n y))
           (set-cdr! x y))
         ds))
    (else ds)))
于 2013-04-28T19:36:24.450 回答
0

改变=等于?

(define (remove-digit digit list)
  (cond ((null? list) list)
        ((equal? digit (car list)) (remove-digit digit (cdr list)))
        (else (cons (car list) (remove-digit digit (cdr list))))))

(display (remove-digit 1 '(1 2 3 (4556 1))))
于 2013-04-28T19:42:02.117 回答