Search code examples
listschemeguile

Scheme Guile: remove only first occurrence from a list (non destructive)


I would need to remove the first occurrence of an element from a list in a non destructive way.

According to the Guile Reference Manual there are a set of functions to do it in a destructive way (delq1!, delv1!, delete1!). On the other hand the non destructive versions remove all the occurrences of the element.

I know I could write a function (may be by means of filter) to do it in a couple of lines but I was wondering if there exist a better/standard method to do it.

As a matter of example, giving the list

((1 2) (3 4) (1 2)) 

when removing the element

(1 2) 

I expect the result be

((3 4) (1 2)) 

whereas the original list remains

((1 2) (3 4) (1 2)).

Thanks in advance!


Solution

  • In Scheme, the standard solution is to create a new list, but without the element. In the documentation, we see that the delete procedure eliminates all occurrences of the element - so we have to roll our own solution, but it's simple:

    (define (delete-1st x lst)
      (cond ((null? lst) '())
            ((equal? (car lst) x) (cdr lst))
            (else (cons (car lst)
                        (delete-1st x (cdr lst))))))
    

    For example:

    (delete-1st '(1 2) '((1 2) (3 4) (1 2)))
    => '((3 4) (1 2))