MAPCAR optimization

MAPCAR optimization

Browning_Zed
Advocate Advocate
1,457 Views
22 Replies
Message 1 of 23

MAPCAR optimization

Browning_Zed
Advocate
Advocate

Hi All,
I have a need to check if the variables v1 v2 v3 "" are equivalent, and if true, then set these variables to nil. To solve this problem, I created the following code:

 

 

(mapcar
	'set '(v1 v2 v3)
	(mapcar
		'(lambda ( x ) (if (= "" x) (setq x nil) x))
		(list v1 va2 v3)
	)
)

 

 

My question is, is it possible to optimize this code so as not to repeat the list of variables twice? That is, exclude the repetition

'(v1 v2 v3) and (list v1 v2 v3) and define the list of variables once.

0 Likes
Accepted solutions (3)
1,458 Views
22 Replies
Replies (22)
Message 21 of 23

ronjonp
Mentor
Mentor

Could even be as simple as this .. assuming that all symbols need to = "" before they get set to nothing.

(if (= "" v1 v2 v3)
  (mapcar 'set '(v1 v2 v3) '(nil nil nil))
)
Message 22 of 23

john.uhden
Mentor
Mentor

@ronjonp 

Once again, since we may not know how many variables are in the list, then...

;; Say (setq lst '(v1 v2 v3 vn))
(and
  (listp lst)
  (vl-every '(lambda (x)(= (eval x) "")) lst)
  (not (foreach item lst (set item nil)))
)
;; Hmm, I think this would work...
(mapcar 'set lst '(nil nil nil nil nil nil nil nil nil etc))

 

John F. Uhden

0 Likes
Message 23 of 23

ronjonp
Mentor
Mentor

@john.uhden wrote:

@ronjonp 

Once again, since we may not know how many variables are in the list, then...

;; Say (setq lst '(v1 v2 v3 vn))
(and
  (listp lst)
  (vl-every '(lambda (x)(= (eval x) "")) lst)
  (not (foreach item lst (set item nil)))
)
;; Hmm, I think this would work...
(mapcar 'set lst '(nil nil nil nil nil nil nil nil nil etc))

 


For sure ... I'd group these as a list like so then just nullify the list as a whole:

(setq l '("" "" ""))
(if (apply '= (cons "" l))
  (setq l nil)
)

I'd like more context as to where the OP is going with this though. Correct structure in code makes a world of difference with these trivial tasks.

0 Likes