Recursion 递归函数不工作'&引用;程序car中的类型参数错误“;
我正在编写一个递归函数,它接受一个元素a和一个列表L,并返回一个等于L的列表,但每次出现一个元素都会被删除。以下是我写的:Recursion 递归函数不工作'&引用;程序car中的类型参数错误“;,recursion,scheme,lisp,cdr,sisc,Recursion,Scheme,Lisp,Cdr,Sisc,我正在编写一个递归函数,它接受一个元素a和一个列表L,并返回一个等于L的列表,但每次出现一个元素都会被删除。以下是我写的: (define (remove A L) (cond ( (eq? A (car L)) (remove A (cdr L)) ) ( (not(eq? A (car L))) (cons (car L) (remove A (cdr L))) ) ( (null? L) '(
(define (remove A L)
(cond ( (eq? A (car L)) (remove A (cdr L)) )
( (not(eq? A (car L))) (cons (car L) (remove A (cdr L))) )
( (null? L) '() )
)
)
编译并运行时,我得到以下错误:
/tmp/compile/5c6515d8-e155-11e5-9605-aa00009baa05/input/main.scheme:2:21: In procedure remove:
/tmp/compile/5c6515d8-e155-11e5-9605-aa00009baa05/input/main.scheme:2:21: In procedure car: Wrong type argument in position 1 (expecting pair): ()
我想出来了:
由于car
和cdr
不能在任何空列表上工作,因此需要对功能进行第一次检查(空?L)
(define (remove A L)
(cond ( (null? L) '() )
( (equal? A (car L)) (remove A (cdr L)) )
( (not(equal? A (car L))) (cons (car L) (remove A (cdr L))) )
)
)
cond
中的最后一个案例应该是else
。事实上,一些方案实现甚至不允许它是其他任何东西。