从Scheme中的列表中删除元素 [英] Delete element from List in Scheme
本文介绍了从Scheme中的列表中删除元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这种形式的清单
( (1 3) (2 2) (3 1) (4 5) (5 1)))
我想删除一个项目,例如(3 1)
and I want to delete an item let's say (3 1)
结果将是
( (1 3) (2 2) (4 5) (5 1)))
我写了这样的东西,我不知道为什么它不能正常运行.
I have written something like this and I do not know why it is not running correctly.
(define (deleteItem list item)
(cond
((equal? item (car list)) (cdr list))
(cons (car list)(deleteItem(cdr list) item))))
推荐答案
There's a built-in function for this, it's called remove
:
(define lst
'((1 3) (2 2) (3 1) (4 5) (5 1)))
(remove '(3 1) lst)
=> '((1 3) (2 2) (4 5) (5 1))
...但是我想您需要从头开始实现它.有关您的代码的一些建议:
… But I guess you need to implement it from scratch. Some suggestions for your code:
- 您不应使用
list
作为参数名称,这将与内置函数发生冲突.让我们将其称为lst
- 大多数列表过程都缺少基本情况:如果列表为空会怎样?
- 在最后一种情况下,您还缺少
else
部分
- You should not use
list
as a parameter name, that'll clash with a built-in function. Let's call itlst
instead - You're missing the base case necessary form most list procedures: what happens if the list is empty?
- You're also missing the
else
part in the last condition
在完成上述所有修复后,该过程将起作用:
With all the above fixes in place, the procedure will work:
(define (deleteItem lst item)
(cond ((null? lst)
'())
((equal? item (car lst))
(cdr lst))
(else
(cons (car lst)
(deleteItem (cdr lst) item)))))
(deleteItem lst '(3 1))
=> '((1 3) (2 2) (4 5) (5 1))
这篇关于从Scheme中的列表中删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文