Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete element from List in Scheme

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))))
like image 641
dionysosz Avatar asked Oct 26 '25 08:10

dionysosz


1 Answers

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:

  • You should not use list as a parameter name, that'll clash with a built-in function. Let's call it lst 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))
like image 115
Óscar López Avatar answered Oct 29 '25 07:10

Óscar López



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!