help-gnu-emacs
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Simple e-lisp question


From: Pascal J. Bourguignon
Subject: Re: Simple e-lisp question
Date: Wed, 15 Apr 2009 00:07:45 +0200
User-agent: Gnus/5.1008 (Gnus v5.10.8) Emacs/22.3 (darwin)

Eric Lilja <mindcooler@gmail.com> writes:

> Hi, I want to write an elisp-function switch2 that should switch the
> first two elements in a list. I came up with this:
>
> (defun switch2 (x)
>   (append (list (second x) (first x)) (nthcdr 2 x))
> )
> (switch2 '(a b c d)) ; Yields (b a c d)
> (switch2 '(a b)) ; Yields (b a)
> (switch2 '(a)) ; Yields (nil a)
> (switch2 '()) ; Yields (nil nil)
>
> The problem is how it handles a list with only one element and an
> empty list. I'm not sure how it should handle only one element, maybe
> return an unmodified list or an empty list? If an empty list is given
> the result should be an empty list.

This is not a lisp question then.  It's a make up your mind question.


> How can I fix my swith2 to cope better with the last two calls above
> and can I use the more fundamental list functions if you know what I
> mean and avoid nthcdr altogether?

So what do you want?


On my part, I'd like it to return the object unmodified if there are
less than two elements or it's not a list.

These kinds of operations are usually named "swap".  Switch means
nothing in this context.  You can switch things on or off, but here
you want to swap.


(defun swap-first-two (object)
   (cond
     ((atom object)        object)
     ((atom (rest object)) object)
     (t  (list* (second object) (first object) (rest (rest object))))))


(defun test/swap-first-two ()
    (equalp '( a
               ()
               (a)
               (a . b)
               (b a)
               (b a . c)
               (b a c)
               (b a c d) )
            (mapcar (function swap-first-two)
                    '( a
                       ()
                       (a)
                       (a . b)
                       (a b)
                       (a b . c)
                       (a b c)
                       (a b c d) ))))

(test/swap-first-two) --> t 


-- 
__Pascal Bourguignon__


reply via email to

[Prev in Thread] Current Thread [Next in Thread]