How to delete an element from a list in scheme

40,374

Solution 1

Your code is almost correct. The item also should be a parameter, so the function may begin with like this:

(define delete
  (lambda (item list)
  ...

Also, your code needs paren around the cdr list and else in the last clause. Then, the code may be like this:

(define delete
  (lambda (item list)
    (cond
     ((equal? item (car list)) (cdr list))
     (else (cons (car list) (delete item (cdr list)))))))

Solution 2

Shido Takafumi wrote a tutorial about Scheme, Yet Another Scheme Tutorial. In chapter 7, exercise 1, the 3rd problem.

A function that takes a list (ls) and an object (x) as arguments and returns a list removing x from ls.

The author gave the solution code bottom of the page.

; 3
(define (remove x ls)
  (if (null? ls)
      '()
      (let ((h (car ls)))
        ((if (eqv? x h)
            (lambda (y) y)
            (lambda (y) (cons h y)))
         (remove x (cdr ls))))))

The code maybe difficult to comprehend for beginner. It's same as the code below.

(define (rm x ls)
  (if (null? ls)
      '()
      (if (eqv? x (car ls))
          (rm x (cdr ls))
          (cons (car ls)
                (rm x (cdr ls))))))

This can delete the same elements in list. :D

Solution 3

1) if consider the input list may be a simple list, or you just want to delete the item in the top-level of a nested list for example:

delete 2 from (1 2 3 4) will return (1 2 3)
delete 2 from (1 2 3 (2 3) 3 2 4) will return (1 3 (2 3) 3 4)

as we can see the 2nd example above, it just delete the item in the top-level of the nested list, within the inner list, we doesn't change it.

this code should be:

(define (deleteitem list1 item) 
( cond
    ((null? list1) ’())
    ((equal? (car list1) item) (deleteItem (cdr list1) item)) 
    (else (cons (car list1) (deleteitem (cdr list1) item)))
))

2) if consider the input list may be a nested list

for example:

input list: (1 2 3 (3 2 (2 4 (2 5 6) 2 5 6) 2 4) 2 3 (2 3 4))

and delete the element 2 in the input list

the output list should be: (1 3 (3 (3 (5 6) 5 6) 4) 3 (3 4))

and the code should be:

(define (delete2 list1 item) 
    ( cond
    ((null? list1) '())
    ((pair? (car list1)) (con (delete2 (car list1) item) (delete2 (cdr list1) item)))
    ((equal? (car list1) item) (delete2 (cdr list1) item)) 
    (else (cons (car list1) (delete2 (cdr list1) item)))
))
Share:
40,374

Related videos on Youtube

nan
Author by

nan

Updated on February 28, 2020

Comments

  • nan
    nan about 4 years

    how to delete an element from a list ex:- list=[1 2 3 4]

    I have come up with some code.I think I got wrong somewhere.

     (define delete item
       (lambda (list)
       (cond
        ((equal?item (car list)) cdr list)
         (cons(car list)(delete item (cdr list))))))
    

Related