【问题标题】:Is there an emacs lisp splat operator or another way of performing this type of operation?是否有 emacs lisp splat 运算符或执行此类操作的其他方式?
【发布时间】:2014-05-16 16:19:16
【问题描述】:

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

(myfunc arg1 nil arg2 arg3)

我需要选择性地(依赖于我们将调用 my_bool 的布尔变量)向此列表添加一个额外的参数,以便函数调用如下所示:

(myfunc arg1 nil arg2 added_argument arg3)

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

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

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

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

我的第三个想法是,如果我们有一个像 rubies' 这样的 splat 运算符,我们可以过滤然后 splat 并且所有内容都会被整理出来,就像这样:

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

但我无法找到一个 splat 运算符(从技术上讲是一个列表解构运算符)(PS 上面的代码是近似的,因为它是一个不起作用的解决方案,所以我确定在那里。

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

提前感谢,对不起我的菜鸟 emacs lisp 技能:(。

【问题讨论】:

  • 参见函数apply,它将函数应用于参数列表。 (另请参阅 lambda 列表关键字 &optional&rest。)

标签: emacs elisp destructuring


【解决方案1】:

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

`(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(apply 'myfunc my-list)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-08
    • 2014-04-17
    • 1970-01-01
    • 2017-05-17
    • 1970-01-01
    • 2023-03-30
    相关资源
    最近更新 更多