Generic Lisp: bind x recursively to a list

I am trying to add, say, x to each element of the list. For example:

(queue 3 '(1 2 3))

will give

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

The code below does not seem to do what I want. Any clues?

(defun queue(x y)
 (cond
  ((null y) nil)
  (t (cons x (queue x (rest y)))))) 
+3
source share
2 answers

You add x to the result of applying the queue to the rest of y, without using the first element of y at all. So basically you throw away all y values ​​and replace them with x.

Instead, you want to do (cons (list x (first y)) (queue x (rest y)))))).

Of course, you can only use the map for this, but I assume this is an exercise in recursion.

+3
source

You already have an answer for the recursive version.

Here is the usual Lisp method using MAPCAR:

(defun queue (item list)
   (mapcar (lambda (list-element)
              (list item list-element))
           list))
+3
source

Source: https://habr.com/ru/post/1723585/


All Articles