TejimaNoHimitsu <····@test.com> writes:
> I'm not sure if this is the right place to ask, but since it is a lisp
> forum I thought it couldn't hurt ;)
>
> 1) Is there any way to test for option arguments in a function? For
> example, if I do:
>
> (defun test (list1 list2 &key k)
>
> is there a way to test in the body of that function whether or not k
> exists? If k doesn't exist, the value is NIL, but I don't know how to
> compare if something's value is NIL. I know I should know, but I
> don't. I would use an if statement, but k is either NIL or the key
> value....
* (defun bar (&key (foo nil supplied-foo-p))
(format t "~%foo is ~A" foo)
(format t "~%foo was ~Aprovided" (if supplied-foo-p "" "not ")))
BAR
* (bar)
foo is NIL
foo was not provided
NIL
* (bar :foo nil)
foo is NIL
foo was provided
NIL
* (bar :foo 'baz)
foo is BAZ
foo was provided
NIL
See 3.4.1 of the CLHS for details.
> 2) is there an easy way to swap items in a list? For example, I
> want to swap the 2nd and 4th items in the list '(1 4 3 2 5).... is
> there an easy way to do it? I can't explicitly set the value of an
> element in a list, can I?
* (defparameter *my-list* '(1 2 3 4 5))
*MY-LIST*
* (rotatef (second *my-list*) (fourth *my-list*))
NIL
* *my-list*
(1 4 3 2 5)
* (setf (third *my-list*) 42)
42
* *my-list*
(1 4 42 2 5)
HTH,
Edi.
--
Dr. Edmund Weitz
Hamburg
Germany
The Common Lisp Cookbook
<http://cl-cookbook.sourceforge.net/>
···@agharta.de (Dr. Edmund Weitz) writes:
> > 2) is there an easy way to swap items in a list? For example, I
> > want to swap the 2nd and 4th items in the list '(1 4 3 2 5).... is
> > there an easy way to do it? I can't explicitly set the value of an
> > element in a list, can I?
>
> * (defparameter *my-list* '(1 2 3 4 5))
> *MY-LIST*
> * (rotatef (second *my-list*) (fourth *my-list*))
> NIL
> * *my-list*
> (1 4 3 2 5)
> * (setf (third *my-list*) 42)
> 42
> * *my-list*
> (1 4 42 2 5)
However, note that it will traverse the list twice to do this. lists
elements are directly accessed, they are obtained by cdr'ing down the
chain of conses each time.
Usually, if you are going to be swapping arbitrary elements, it's a
hint that you do not want a list as your basic data structure. This
is a basic issue of algorithmic design and would be true in any
language, except languages that lie to you and tell you that they have
a list data structure when really they are using an array.