You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:修复Scheme语言中remove函数的执行报错问题

修复Scheme中remove过程的报错问题

问题背景

已有实现好的filter-lst过程:

(define (filter-lst fn lst)
    (if (null? lst)
        lst
        (if (fn (car lst))
            (cons (car lst)
                  (filter-lst fn (cdr lst))
                  )
            (filter-lst fn (cdr lst))
            )
        )
    )

需求是实现remove过程,接收一个列表,返回移除所有指定item元素后的新列表(列表仅含数字,无嵌套),可借助上述filter-lst过程。

用户编写的代码执行报错,错误信息:

application: not a procedure;
 expected a procedure that can be applied to arguments
  given: '(1 3 5)

用户原代码:

(define (remove item lst)
    (cond ((null? lst) '())
     (equal? item (car (lst))(remove item (cdr lst)))
            (else (cons (car lst)(remove item (cdr (lst)))))
            )
  )
;;; Tests
(remove 3 null)
; expect ()
(remove 3 '(1 3 5))
; expect (1 5)
(remove 5 '(5 3 5 5 1 4 5 4))
; expect (3 1 4 4)

错误原因

  1. 错误地将列表参数当作过程调用:代码里(car (lst))和(cdr (lst))是错误写法,lst是传入的列表参数,不是过程,不需要加括号,直接写(car lst)、(cdr lst)即可。
  2. cond子句语法错误:第二个子句的条件和表达式没有正确分隔,cond的每个子句应该是(条件 表达式)的形式,原代码里把条件和表达式写在了同一个括号里,语法不合法。

修复方案

方案1:修正原cond版本的代码

修正后的代码:

(define (remove item lst)
  (cond
    ((null? lst) '())
    ((equal? item (car lst)) (remove item (cdr lst)))
    (else (cons (car lst) (remove item (cdr lst))))
  )
)

方案2:借助filter-lst实现(更简洁)

根据提示,filter-lst是过滤列表的过程,我们只需要传入一个判断元素不等于item的匿名函数即可:

(define (remove item lst)
  (filter-lst (lambda (x) (not (equal? x item))) lst)
)

测试验证

两种方案都能通过给定的测试用例:

  • (remove 3 null) 返回 ()
  • (remove 3 '(1 3 5)) 返回 (1 5)
  • (remove 5 '(5 3 5 5 1 4 5 4)) 返回 (3 1 4 4)

内容的提问来源于stack exchange,提问作者Proteus Yi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 15:52:17