TheSwamp

Code Red => AutoLISP (Vanilla / Visual) => Topic started by: mailmaverick on February 15, 2017, 08:30:03 AM

Title: Use Operator from Variable
Post by: mailmaverick on February 15, 2017, 08:30:03 AM
Is it possible to give + or - operators through variables ?
Such as
(setq op '+)
(op 5 2)
Result = 7

(setq op '-)
(op 5 2)
Result = 3



Title: Re: Use Operator from Variable
Post by: mailmaverick on February 15, 2017, 08:42:15 AM
Found one solution using apply :
(setq op '+)
(apply op (list 5 2))
Result = 7

(setq op '-)
(apply op (list 5 2))
Result = 3

Is there any other solution ?


Title: Re: Use Operator from Variable
Post by: Grrr1337 on February 15, 2017, 08:47:41 AM
To shed some light:
Code: [Select]
_$ (type +)
SUBR
_$ (type '+)
SYM

_$ (setq op +)
#<SUBR @000000097244fba8 +>
_$ (op 5 2)
7
_$ (eval '(op 5 2))
7

_$ (setq op '+)
+
_$ (apply op '(5 2))
7
EDIT: Another way would be to use the read function, so this thread (https://www.theswamp.org/index.php?topic=52189.0) is somewhat related.
Title: Re: Use Operator from Variable
Post by: irneb on February 15, 2017, 08:52:03 AM
Both those would work, though only with a few tweaks. It's one of the features of Lisp in general. There's no difference between an "operator" and a function, in Lisp (all Lisp's not just AutoLisp) everything is a function or a value, and both can be assigned to a symbol.

Code - Auto/Visual Lisp: [Select]
  1. (setq op +)
  2. (op 5 2)
  3. ;; Result = 7

Or if you quote the "operator", then you need to "de-quote" it when you use it - i.e. use something like apply which takes a quoted symbol of the function instead of just the function. Thus:
Code - Auto/Visual Lisp: [Select]
  1. (setq op '+)
  2. (apply op '(5 2))
  3. ;; Result = 7
Title: Re: Use Operator from Variable
Post by: mailmaverick on February 15, 2017, 09:53:47 AM
Thanks a lot. My query is resolved.
Title: Re: Use Operator from Variable
Post by: dgorsman on February 15, 2017, 10:14:38 AM
I've done that in the past.  I needed a means to mass-convert drawing content in terms of layers, line types, color, and so on.  Naturally the drawings could not be counted on to even be consistently wrong.  So I built an expert system (http://"https://en.wikipedia.org/wiki/Expert_system") in LISP, using (apply ...) frequently to apply both math and logic rules.  Worked quite well except rules had to be constructed manually which was time consuming.