Help with MAPCAR

Help with MAPCAR

msarqui
Collaborator Collaborator
947 Views
3 Replies
Message 1 of 4

Help with MAPCAR

msarqui
Collaborator
Collaborator

Hi guys, may I have some help please?

 

I swear I tried to learn MAPCAR but it is too much to my limited brain...
So, why this is not working?

 

(defun c:Highlight ( / typ color i e)
(setq typ (ssget))
;Highlight the objects with custom color
(repeat
	(setq i (sslength typ))
	(setq e (ssname typ (setq i (1- i))))
	(setq color (cons (vla-get-color (vlax-ename->vla-object e)) color));Save the colors in a list
	(vla-put-color (vlax-ename->vla-object e) 3)
	(redraw e 3)
);repeat
(alert "Selected objects in green"); Actually, here I will put my routine
;Unhighlight the objects with the original color
(repeat (setq i (sslength typ))
	(setq e (ssname typ (setq i (1- i))))
	(mapcar '(vla-put-color (vlax-ename->vla-object e)) color);Re-assign the original colors to each object
	(redraw e 4)
);repeat
)

Thanks,

Marcelo

0 Likes
Accepted solutions (1)
948 Views
3 Replies
Replies (3)
Message 2 of 4

martti.halminen
Collaborator
Collaborator

 

MAPCAR is used to map a function over one or more lists, that is calling the function with all the first elements as its parameters, then all the second elements etc., and collecting the result:

 

(setq aa '(1 2 3 4) bb '(10 20 30 40) cc '(100 200 300 400 500))
(100 200 300 400 500)
_$
_$ (mapcar '+ aa bb)
(11 22 33 44)
_$ (mapcar '+ aa bb cc)
(111 222 333 444)

- note: if the lists are of differing lengths, only handles the items up to the length of the shortest list


_$ (mapcar (lambda (x) (* x x)) aa)
; error: bad function: #<USUBR @0000000031a3c5e8 -lambda->
_1$
; reset after error

-- so, a quote needed also when using lambda clauses (unnamed function definitions) instead of normal named functions
_$ (mapcar '(lambda (x) (* x x)) aa)
(1 4 9 16)

 

Also, note that it handles Lisp lists, not selection sets.

 

-- 

0 Likes
Message 3 of 4

martti.halminen
Collaborator
Collaborator
Accepted solution

 

You could try replacing your second REPEAT call with this:

 

(mapcar '(lambda (e c)
          (vla-put-color (vlax-ename->vla-object e) c)
          (redraw e 4))
        (sset-to-list typ)
        color)


- that calls a helper function:

(defun sset-to-list (sset / res num len)
  ;; AutoLISP selection set dumped to a list of enames
  (setq len (sslength sset)
        num 0)
  (while (< num len)
    (setq res (cons (ssname sset num) res))
    (setq num (1+ num)))
  (reverse res))

- untested

 

- as a style point, you could rename your COLOR variable as COLORS, so that the reader can guess that it contains more than one color

0 Likes
Message 4 of 4

msarqui
Collaborator
Collaborator
Many thanks martti.halminen
I will take a look and try to learn.
0 Likes