Bill Tillman 发表于 2022-7-6 06:27:35

Mapcar for (if (= ....

I have an exercise this morning I'm working on and thought why not make use of the time to learn more about mapcar/lambda.
 
I have four variables:
 
 
If any of these variables contains the value of "Y" I want to take some action. I've been doing this in the past:
 

(if (or (= front "Y") (= back "Y") (= rside "Y") (= lside "Y")) (setq a "Y"))
 
All the examples I've searched through so far show how to add 1, subtract 2, strcase, etc... How would one run this process through mapcar/lambda to achieve the same results? Or would this not be a good example of where to use mapcar in lieu of the above (if (or statement?

pBe 发表于 2022-7-6 06:47:43

Based on your example for value assign to variable A
 

(setq a (vl-some             '(lambda (v)                  (if (eq (eval v) "Y")                        "Y"))             '(front back rside lside)))
 
or if you want to see what variable has the value "Y"

(vl-some   '(lambda (v)            (if (eq (eval v) "Y")                  v))   '(front back rside lside))
 
EDIT: Man, i saw a similar sugesstion by Ron at the swamp.

BlackBox 发表于 2022-7-6 07:07:06

 
 
Consider:

(setq a      (car      (vl-remove-if-not          (function (lambda (x) (= "Y" x)))          (list front back rside lside)      )      ))
 
Speed test:

(defun _foo1 () (vl-some   '(lambda (v)      (if (eq (eval v) "Y")      "Y"      )    )   (list front back rside lside) ))(defun _foo2 () (car   (vl-remove-if-not   (function (lambda (x) (= x "Y")))   (list front back rside lside)   ) ))
 
... Result from console:

_FOO1 _FOO2 _$ (bench '(_foo1 _foo2) '() 10000)_FOO1Elapsed: 733Average: 0.0733_FOO2Elapsed: 63Average: 0.0063_$

pBe 发表于 2022-7-6 07:17:09

 
I'm sold

BlackBox 发表于 2022-7-6 07:29:28

 
Cheers, pBe
页: [1]
查看完整版本: Mapcar for (if (= ....