How to remove an item from a list in a schema

how to remove an item from ex list: - list = [1 2 3 4]

I came up with some kind of code. I think I’ve made a mistake somewhere.

 (define delete item
   (lambda (list)
   (cond
    ((equal?item (car list)) cdr list)
     (cons(car list)(delete item (cdr list))))))
+3
source share
5 answers

Your code is almost correct. The parameter itemmust also be a parameter, so the function can start as follows:

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

In addition, your code needs a couple around cdr listand elsein the last section. Then the code could be like this:

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

Shido Takafumi wrote a tutorial on Scheme, Another Schema Tutorial . In chapter 7, complete exercise 1, the third problem.

, (ls) (x) , x ls.

.

; 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))))))

. , .

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

.: D

+3

1), :

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)

, , .

:

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

2),

:

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

2

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

:

(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)))
))
+1

, , :

(define (delete element lst)
    (let loop ([temp lst])
        (if (= element (car temp)) (cdr temp)
            (cons (car temp) (loop (cdr temp))))))
0
(define (deleteItem(list item))
    (cond
    ((eq ? item (car(list)))cdr(list))
    (cons(car(list)(deleteItem(cdr list)))
    )
)
-3
source

Source: https://habr.com/ru/post/1725686/


All Articles