Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Path: utzoo!watmath!clyde!cbosgd!ihnp4!houxm!whuxl!whuxlm!akgua!gatech!seismo!mcvax!cernvax!cui!manuel From: manuel@cui.UUCP Newsgroups: net.lang.lisp Subject: programming trick Message-ID: <136@cui.UUCP> Date: Fri, 28-Feb-86 17:43:28 EST Article-I.D.: cui.136 Posted: Fri Feb 28 17:43:28 1986 Date-Received: Sun, 2-Mar-86 07:39:51 EST Reply-To: manuel@cui.UUCP (James Stewart) Organization: University of Geneva/Switzerland Lines: 49 I've often run into the problem of wanting to apply a function to every element of a list, but been stuck because the function takes more than one argument. As a simple example: (defun F (x y) (+ x y)) (setq L '(2 4 6 8)) How do we add 10 to each element of L? (mapcar 'F L '10) ; Error: bad list argument to map (mapcar 'F L '(10)) ; (12) (mapcar 'F L '(10 10 10 10)) ; (12 14 16 18) (mapcar '(lambda (x) (F x 10)) L) ; (12 14 16 18) The first example doesn't work for obvious reasons. The second returns a list whose length is the minimum of the argument lists which were given to mapcar. The third works correctly, but is cumbersome because we first had to know that the length of L was 4. The fourth is the best solution, but obscures the code because the number 10 has been hidden inside the lambda (this gets much worse for more complicated expressions). It would be better to have something with the form of the first or second examples. The following trick can be used to do this: (defun repeated (x) ; returns an 'infinite' list of x's ((lambda (list-x) (rplacd list-x list-x)) (list x))) (mapcar 'F L (repeated '10)) ; (12 14 16 18) The 'repeated' function returns a CONS cell whose CDR points to the cell itself. This results in an (apparant) infinite list of x's. Using this as an argument list to mapcar is clearer and doesn't depend on the lengths of the other argument lists. In general, it also costs less in space and in time. Hope this helps ... James Stewart University of Geneva UUCP: seismo!mcvax!cernvax!cui!manuel BITNET: stewart@cgeuge52