0

This is my lisp code.

(defun f (lst)
                (append (subst (last lst) (first lst) (car lst))
                (subst (first lst) (last lst) (cdr lst)))
                )

(f '(a b c d))

This code's output is (D B C . A)

The function works well, but it does not finish because of symbol. I want make (D B C A) without symbol.

How do I fix it? Or is there a better way?

I would appreciate a help.

MinSeob Lim
  • 101
  • 1
  • 3
  • 9
  • Please format your code properly and explain what the function is supposed to do. – sds Mar 06 '17 at 17:19

3 Answers3

2

Assuming that you are meaning to do something like this, you could try using rotatef:

? (setf lst '(a b c d))
(A B C D)
? lst
(A B C D)
? (rotatef (nth 0 lst) (nth (- (length lst) 1) lst))
;Compiler warnings :
;   In an anonymous lambda form at position 0: Undeclared free variable LST (3 references)
NIL
? lst
(D B C A)
Community
  • 1
  • 1
GDP2
  • 1,948
  • 2
  • 22
  • 38
1

Assuming you want to swap the first and last elements, here is an implementation which does that. It traverses the list three times and copies it twice: it is possible to do much better than this, but not without being reasonably devious (in particular I'm reasonably sure a naive implementation with rotatef also traverses it three times although it only copies it once as you need an initial copy of the list, since rotatef is destructive):

(defun swapify (list)
  ;; swap the first and last elements of list
  (if (null (rest list))
      list
      (cons (first (last list)) ; 1st traversal
            (append (butlast (rest list)) ; 2nd and third traversals
                    (list (first list))))))

And here is the devious implementation which traverses the list exactly once. This relies on tail-call elimination: a version which uses a more straightforward loop is fairly obvious.

(defun swapify (list)
  ;; return a copy of list with the first and last elements swapped
  (if (null (rest list))
      list
      (let ((copy (cons nil nil)))
        (labels ((walk (current tail)
                   (if (null (rest tail))
                       (progn
                         (setf (first copy) (first tail)
                               (rest current) (cons (first list) nil))
                         copy)
                       (progn
                         (setf (rest current) (cons (first tail) nil))
                         (walk (rest current) (rest tail))))))
          (walk copy (rest list))))))
0

the symbol is because you are appending a list to an element, if you turn the element into a list using: (list (car lst)) with the same code and it will no longer have the symbol.