简体   繁体   English

SCHEME从列表中删除原子值

[英]SCHEME remove atomic value from a list

I need to do a function where I send a value, and check in the list if there is an equal value to remove it. 我需要执行一个函数,在其中发送一个值,并检查列表中是否存在相等的值以将其删除。 Here are some examples: 这里有些例子:

(elimina 1 '(a b c))            => (a b c)
(elimina 'b '(a (b) c))         => (a () c)
(elimina 1  '(0 (1 (2) 1) 0))   => (0 ((2)) 0)

I tried this: 我尝试了这个:

(define (elimina v1 lista)
  (cond ((null? lista)'())

        ((list? (first lista))
         (list (elimina v1 (first lista))))

        (else
         (if(equal? v1 (first lista))
           (elimina v1 (cdr lista))
           (append (cons (first lista) (elimina v1 (cdr lista))))))
   )
)

And my results where like this: 我的结果是这样的:

(elimina 1 '(a b c))         => (a b c)
(elimina 'b '(a (b) c))      => (a ())
(elimina 1  '(0 (1 (2) 1) 0) => (0 ((2)))

for some reason the last value on the list isn't showing. 由于某种原因,列表中的最后一个值未显示。 Hope someone can help. 希望有人能帮忙。

Thanks! 谢谢!

1) Your problem is here: 1)您的问题在这里:

((list? (first lista))
         (list (elimina v1 (first lista))))

When you recurse into a sublist, you don't process the rest of the list anymore. 当您递归到子列表时,您将不再处理列表的其余部分。

2) Also, 2)而且

(append (cons (first lista) (elimina v1 (cdr lista))))))

can be simplified, because you're appending a list to nothing, so just drop append . 可以简化,因为您没有将列表追加到任何内容,因此只需删除append

3) Not an error, but I recommend you use either first , second , rest ... or car , cadr , cdr ... 3)不是错误,但我建议使用firstsecondrest ...... 或者 carcadrcdr ...

Try: 尝试:

(define (elimina v1 lista)
  (cond 
    ((null? lista) '())
    ((list? (first lista)) 
     (cons (elimina v1 (first lista)) (elimina v1 (rest lista)))) ; <= (1)
    (else
     (if (equal? v1 (first lista))
         (elimina v1 (rest lista))
         (cons (first lista) (elimina v1 (rest lista)))))))       ; <= (2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM