【问题标题】:Recursive function not working '"Wrong type argument in procedure car"递归函数不起作用'“过程车中的错误类型参数”
【发布时间】:2016-03-03 14:46:59
【问题描述】:

我正在编写一个递归函数,它接受一个元素 A 和一个列表 L,并返回一个等于 L 的列表,但每次出现的 A 都会被删除。这是我写的:

(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): ()

【问题讨论】:

    标签: recursion scheme lisp cdr sisc


    【解决方案1】:

    我想通了:

    函数的第一次检查需要(null? L) 为car 和cdr 不能在任何空列表上工作。

    (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 中的最后一个 case 应该是 else。事实上,一些 Scheme 实现甚至不允许它是其他任何东西。
    猜你喜欢
    • 2015-06-20
    • 2018-07-14
    • 2020-06-28
    • 1970-01-01
    • 1970-01-01
    • 2018-04-02
    • 2014-04-03
    • 2018-03-31
    相关资源
    最近更新 更多