我该如何申请“或"?到elisp中的列表 [英] How do I apply "or" to a list in elisp
问题描述
在elisp中,我可以像+一样求值或作为函数.
In elisp I can evaluate or as a function just like +.
(or nil 0 nil) ==> 0
(+ 1 0 1) ==> 2
我可以使用Apply将+应用于列表
I can use apply to apply + to a list
(apply '+ '(1 0 1)) ==> 2
所以,我会以相同的方式思考或工作,但事实并非如此.
So, I would think or would work the same way, but it doesn't.
(apply 'or '(nil 0 nil)) ==> error: (invalid-function or)
我想象这是由一些用于实施短路评估的内部魔术所引起的.如何使用apply在列表上执行或操作?
I imagine this comes from some internal magic used to implement the short-circuit evaluation. How can I use apply to execute the or operation over a list?
P.S.我想要的应用程序是查找命令行上是否有任何元素与特定模式匹配,因此我正在编写的重要部分是:
P.S. my desired application is to find out whether any elements on the command line match a particular pattern, so the important part of what I am writing is:
(apply 'or (mapcar (lambda (x) (string-match-p "pattern" x)) command-line-args))
但这不起作用
推荐答案
问题是or
是一个宏(这是有问题的内部魔术"),而您正确地做到了这一点,因此它可以做短路.如果or
是一个函数,则对其进行调用将需要遵循评估函数调用的通常规则:在进行调用之前,所有参数都需要进行求值.
The problem is that or
is a macro (which is the "internal magic" in question), and you're right that that's done so it can do short-circuiting. If or
was a function, then calling it would need to follow the usual rules for evaluating a function call: all the arguments would need to get evaluated before the call is made.
另请参见此问题- -这是关于Scheme的,但问题完全相同.
See also this question -- it's about Scheme but it's the exact same issue.
对于解决方案,您可能应该使用some
,如:
As for a solution, you should probably use some
, as in:
(some (lambda (x) (string-match-p "pattern" x)) command-line-args)
注意:这使用默认情况下emacs中不包含的通用lisp.只需使用(require 'cl)
Note: this uses common lisp that is not included in emacs by default. Just use (require 'cl)
这篇关于我该如何申请“或"?到elisp中的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!