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: Drew Adams
Subject: RE: Simple e-lisp question
Date: Tue, 14 Apr 2009 13:39:59 -0700

> switch the first two elements in a list.
> 
> (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.
> 
> 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?

Lisp is English. If you can describe it clearly, you can code it.

If x has at least 2 elements, then 2nd, 1st, 3rd...
Else x

at least 2 = cdr
2nd        = cadr
1st        = car
3rd...     = cddr

(defun switch2 (x)
  (if (cdr x)
      (cons (cadr x) (cons (car x) (cddr x)))
    lst))

Hope this wasn't your only homework. ;-)





reply via email to

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