Use conditional places in setf

Suppose I have two variables and I want to set a variable with a lower value to nil.

Is it possible to make it work this way?

(setf a1 5) (setf a2 6) (setf (if (< a1 a2) a1 a2) nil ) 
+4
source share
3 answers

If you want to do something close to this, you can use (setf (symbol-value var) ...) :

 > (defparameter a1 5) > (defparameter a2 6) > (setf (symbol-value (if (< a1 a2) 'a1 'a2)) nil) > a1 nil > a2 6 

To get the syntax closer to the one in your question, you can define setf-expander for if :

 (defsetf if (cond then else) (value) `(progn (setf (symbol-value (if ,cond ,then ,else)) ,value) ,value)) 

Then you can write (setf (if (< a1 a2) 'a1 'a2) nil)

However, the best way to write code is probably to do it directly, using if forms with setf in both branches:

 (if (< a1 a2) (setf a1 nil) (setf a2 nil)) 
+9
source

No, because the if form if not a place, and therefore not capable of setf .

0
source

Although this is not very useful in itself, you may consider this as a small hint:

 (defun new-values (xy) (if (< xy) (values nil y) (values x nil))) (setf a1 5) (setf a2 6) (setf (values a1 a2) (new-values a1 a2)) 
0
source

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


All Articles