I'm learning lisp and I have to return modified input arguments from my function in Lisp.
Consider this easy example:
(defun swap (l1 l2)
(let ((temp))
(setf temp l1)
(setf l1 l2)
(setf l2 temp)))
(setf a (list 1 2 3))
(setf b (list 7 8 9))
(swap a b)
(print a)
(print b)
It doesn't work because I don't know how to pass reference to variable to function. Is that even possible in lisp? How can this function be solved?
UPDATE
;;; doesn't change original
(defun foo1 (x)
(setf x (list 0 0 0)))
;;; but this does
(defun foo4 (x)
(setf (car x) 0)
(setf (cdr x) (list 0 0)))
The reason why I wanted to pass a variable by reference to be able to change it is that, when I have function with 3 input arguments and that function should change all of them, I think it is more elegant to change them by reference, then return list of three variables and then overwrite with them original variables:
;;; more elegant function
(defun foo (x y z)
;;... some work ...
;; Lets PRETEND this does work
(setf x new-x)
(setf y new-y)
(setf z new-z))
; after this, a,b,c will have new values
(foo a b c)
;;; less elegant function
(defun foo (x y z)
;; ... some work ...
(list new-x new-y new-z))
; after this, I still will have to manually set a,b,c
(setf temp (foo a b c))
(setf a (nth 0 tmp))
(setf b (nth 1 tmp))
(setf c (nth 2 tmp))
To explain why I'm trying to accomplish this is I got Hanoi towers homework. I was thinking about using three lists as stacks
and use pop
and push
functions on them to insert and remove the "discs". I defined (move n source target temp)
function, and it is recursively calling itself with n-1
change. The problem is, when I pop
or push
stack in recursive function, it doesn't influence stacks outside.
If I want my move
function to return stacks after n
movements, should I really return list of new stacks (that less elegant function) instead of editing them by reference (that more elegant function)
What is the proper way in Functional languages?