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:
((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,
(append (cons (first lista) (elimina v1 (cdr lista))))))
can be simplified, because you're appending a list to nothing, so just drop append
.
3) Not an error, but I recommend you use either first
, second
, rest
... or car
, cadr
, cdr
...
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)