How to delete an element from a list in scheme

前端 未结 5 1835
渐次进展
渐次进展 2020-12-19 18:26

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         


        
5条回答
  •  轮回少年
    2020-12-19 18:50

    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

提交回复
热议问题