I have list in this form
( (1 3) (2 2) (3 1) (4 5) (5 1)))
and I want to delete an item let's say (3 1)
So the result will be
( (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 as a parameter name, that'll clash with a built-in function. Let's call it lst insteadelse part in the last conditionWith 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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With