emacs - 是否有 emacs lisp splat 运算符或其他执行此类操作的方法?

标签 emacs elisp destructuring

我有一个对变量列表进行操作的运算符,如下所示:

(myfunc arg1 nil arg2 arg3)

我需要有选择地(依赖于我们称之为 my_bool 的 bool 变量)向这个列表添加一个额外的参数,这样函数调用将如下所示:

(myfunc arg1 nil arg2 added_argument arg3)

我的第一个想法是像这样用一个 if block 来做到这一点:

(myfunc arg1 nil arg2 (if mybool t nil) arg3)

但如果 mybool 等于 nil ,这将导致 nil,这是函数语法不允许的。

我的第二个想法是,也许我们可以过滤列表中的 nil 并将其删除,但我们不能这样做,因为 nil 最先出现(或者更确切地说,我想不出办法,我会很高兴被证明是错误的,只是在寻找解决方案)。

我的第三个想法是,如果我们有一个像 Ruby 那样的 splat 运算符,我们可以过滤然后 splat,然后所有的东西都会被整理出来,就像这样:

(myfunc arg1 nil (mysplat arg2 (filter (!= nil) (if mybool t nil)))) arg3)

但我一直没能找到一个 splat 运算符(从技术上讲是一个列表解构运算符)(附言,上面的代码是近似的,因为它是一个不起作用的解决方案,所以我敢肯定。

所以我的问题是如何有选择地向函数调用添加单个参数,并且如果我们不这样做则不产生 nil 作为该参数。

提前致谢,抱歉我的新手 emacs lisp 技能 :(。

最佳答案

您可以在反引号内使用拼接运算符,@:

`(arg1 nil arg2 ,@(if my-bool (list added-argument) nil) arg3)

即如果my-bool为真,则在列表中间拼接(list added-argument)创建的列表,否则拼接在nil - 这是一个空列表,因此不添加任何元素。参见 the Backquote section of the Emacs Lisp manual获取更多信息。

(一旦你创建了这个列表,看起来你会想要使用 apply 来调用带有可变数量参数的 myfunc: (应用'myfunc my-list))

关于emacs - 是否有 emacs lisp splat 运算符或其他执行此类操作的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23700103/

相关文章:

emacs - 在 emacs 中的最后两个缓冲区之间来回切换

Emacs - 找不到关于电子布局模式的信息

javascript - 当连字符在属性中时如何解构 e.target?

Javascript解构并分配给新对象

emacs - 我编写的 Emacs 函数上的 "wrong-type-argument"

emacs - 为什么emacs中没有代码折叠?

emacs - 在 .emacs 中获取不带扩展名的缓冲区文件名

emacs - Emacs + AUCtex 下的 knit 和 latexmk 的一次性命令

emacs - 关于如何编写 Emacs 模式的好资源?

Javascript (Node.js) 将 json 解构为现有变量