knowledge-database (beta)

Current group: comp.lang.lisp

swapping two elements of a list

swapping two elements of a list  
Jim Newton
 Re: swapping two elements of a list  
Edi Weitz
From:Jim Newton
Subject:swapping two elements of a list
Date:Mon, 24 Jan 2005 00:40:43 +0100
Is there a better way to swap two elements of a list?
This is how i'm doing it, but it seems overly complicated.

(defun swap-elements ( the-list a b)
(rotatef (car (member a the-list))
(car (member b the-list))))
From:Edi Weitz
Subject:Re: swapping two elements of a list
Date:Mon, 24 Jan 2005 00:57:28 +0100
On Mon, 24 Jan 2005 00:40:43 +0100, Jim Newton wrote:

> Is there a better way to swap two elements of a list? This is how
> i'm doing it, but it seems overly complicated.
>
> (defun swap-elements ( the-list a b)
> (rotatef (car (member a the-list))
> (car (member b the-list))))

I don't think it's complicated. The only problem I see is that it
traverses THE-LIST twice which you might want to avoid for very long
lists. In that case I'd do it like this (untested):

(defun swap (list a b &key (test #'eql))
(let* ((part-1 (member-if (lambda (x)
(or (funcall test x a)
(funcall test x b)))
list))
(other (cond ((funcall test (car part-1) a) b)
(t a)))
(part-2 (member other part-1 :test test)))
(when part-2
(rotatef (car part-1) (car part-2)))))

Cheers,
Edi.

--

Lisp is not dead, it just smells funny.

Real email: (replace (subseq "spamtrap@agharta.de" 5) "edi")
   

Copyright © 2006 knowledge-database   -   All rights reserved