Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use conditional places in setf

Lets say I have two variables and I want to set the variable with 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
)
like image 854
Buksy Avatar asked Jan 14 '23 10:01

Buksy


1 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 a syntax closer to the one in your question, you can define an setf-expanderfor 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 of writing the code is probably to do it straight forward, using an if with setf forms in both branches:

(if (< a1 a2) 
    (setf a1 nil)
    (setf a2 nil))
like image 119
Terje D. Avatar answered Feb 01 '23 04:02

Terje D.