[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.lisp

Re: how to remove but preserve tail.

William James

4/1/2015 8:32:00 AM

Thomas A. Russ wrote:

> > So can someone think of a clever way with LOOP to
> > write remove-preserving-tail, only iterating until the
> > to-be-deleted element is encountered? I only want to remove the
> > first occurance in my case.
>
> Hmm. It would seem a recursive solution might be simpler, but if it has
> to be loop, how about:
>
> (defun remove-1-sharing-tail (item list)
> (loop for remainder on list by #'cdr
> when (eql item (first remainder))
> return (nconc head (rest remainder))
> else collect (first remainder) into head
> finally (return list)))
>
>
>
> USER> (setq foo (list 1 2 3 4 5 6 7 3))
> (1 2 3 4 5 6 7 3)
> USER> (setq bar (remove-1-sharing-tail 3 foo))
> (1 2 4 5 6 7 3)
> USER> (eq foo bar)
> NIL
> USER> (eq (cdddr foo) (cddr bar))
> T

Gauche Scheme:

(define foo (list 1 2 3 4 5 6 7 8))

(use srfi-1) ; span
(define (remove-1-sharing-tail item things)
(receive (a b)
(span (^x (not (equal? x item))) things)
(append! a (drop* b 1))))

(define bar (remove-1-sharing-tail 2 foo))
bar
===>
(1 3 4 5 6 7 8)

(eq? (cddr foo) (cdr bar))
===>
#t