tags:

views:

93

answers:

2

I'm trying to add, say, x to every element of a list. For example:

(queue 3 '(1 2 3))

would give

((3 1) (3 2) (3 3))

The code below apparently does not do what I want. Any hints please?

(defun queue(x y)
 (cond
  ((null y) nil)
  (t (cons x (queue x (rest y))))))
+3  A: 

You're prepending x to to the result of applying queue to the rest of y, without using y's first element at all. So basically you're throwing away all values of y and replacing them with x.

You want to do (cons (list x (first y)) (queue x (rest y)))))) instead.

You could of course just use map to do this, but I assume this is an exercise in recursion.

sepp2k
Perfect! And the explanation was pretty descriptive. Thanks!
qwerty
+3  A: 

You've got the answer for the recursive version already.

Here is the usual Lisp way using MAPCAR:

(defun queue (item list)
   (mapcar (lambda (list-element)
              (list item list-element))
           list))
Rainer Joswig