Welcome to W3Courses
 Like Us on Facebook

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

The following code deletes the Nth occurrence of an element from a list without using Set!

CODE
 (define (aux L X N C)
      (cond ((null? L) L)
            ((eqv? (car L) X)
                   (cond ((eqv? C 1) (aux (cdr L) X N  N))
                           (else (cons (car L) (aux (cdr L) X N (- C 1))))))
                   (else (cons (car L) (aux (cdr L) X N C)))))))

(define (deleteN L X N)
      (letrec ((daux aux))
             (daux L X N N)))


RESULT
> (deleteN '(a b a a a) 'a 3)
(a b a a)

Share