Welcome to W3Courses
 Like Us on Facebook

Delete the Nth Occurrence of an Element from a List with Set! Using Scheme Source Code

The following code deletes the Nth occurrence of an element from a List with Set!

CODE
(define z 1)
(define (ndelete n x y)
       (cond ((null? y) '())
              ((eqv? x (car y)) (cond ((< z n) (set! z (+ z 1)) (cons (car y) (ndelete n x (cdr y))))
                      (else (set! z 1) (ndelete n x (cdr y)))))
              (else (cons (car y) (ndelete n x (cdr y))))))


RESULT
> (ndelete 2 'a '(a b a b a a))
(a b b a)
> (ndelete 1 'a '(a b a g a f a))
(b g f)
> (ndelete 5 'b '(a b b b a b b a b))
(a b b b a b a b)


 

Share