我需要完全从列表中删除给定的数字。这将输入:
(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))))))
但无法从列表中的列表中删除。任何帮助非常感谢
答案 0 :(得分: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))))))
答案 1 :(得分:0)
(define (rem-dig n ds)
(cond
((list? ds)
(remove-digit n (map (lambda(d)(rem-dig n d)) ds)))
(else ds)))
需要将等号谓词从特定于数字的=
替换为普通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)))
答案 2 :(得分: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))))