【问题标题】:Emacs Lisp: evaluate variable in alistEmacs Lisp:评估 alist 中的变量
【发布时间】:2009-11-02 22:42:41
【问题描述】:

这可能很愚蠢,但我没有足够的 Elisp 知识来理解引用和评估方面的情况。

假设我有这个 Elisp 代码:

(add-to-list 'default-frame-alist '(width . 100))
(add-to-list 'default-frame-alist '(height . 50))

这将导致预期的 default-frame-alist 值:

((height 50)
 (width 100))

但是现在如果我有这个:

(setq my-frame-width 100)
(setq my-frame-height 50)
(add-to-list 'default-frame-alist '(width . my-frame-width))
(add-to-list 'default-frame-alist '(height . my-frame-height))

这将导致 -

((height my-frame-height)
 (width my-frame-width))

并且,从框架几何来看,从不评估这些变量。如何使 my-frame-width 和 height 的实际值出现在此 alist 中?我的引号太多了吗?但我无法从添加到列表评估中删除任何内容...

【问题讨论】:

    标签: elisp


    【解决方案1】:

    试试这个:

    (setq my-frame-width 100)
    (setq my-frame-height 50)
    (add-to-list 'default-frame-alist `(width . ,my-frame-width))
    (add-to-list 'default-frame-alist `(height . ,my-frame-height))
    

    使用反引号代替引号允许您使用 , 来强制评估参数。

    请参阅 Elisp 参考手册。键入 C-x info,搜索 elisp 参考手册,然后在其中搜索反引号。

    【讨论】:

    • 正是我想要的,谢谢!像这样的问题提醒我,我应该花时间系统地学习 elisp。
    • 类似问题请参见Emacs lisp evaluate variable in alist..
    • 我喜欢反引号和逗号的直观显而易见性。
    【解决方案2】:

    作为mch 答案中的反引号运算符的替代方法,您可以使用cons 函数。这个函数将构建一个 cons 单元,第一个参数作为它的 car,第二个参数作为它的 cdr。代码中的点对符号是对此的简写。所以我们可以这样重写你的代码:

    (setq my-frame-width 100)
    (setq my-frame-height 50)
    (add-to-list 'default-frame-alist (cons 'width my-frame-width))
    (add-to-list 'default-frame-alist (cons 'height my-frame-height))
    

    这样,您可以引用您想要按字面显示的符号(如宽度和高度)并评估您需要其值的符号(如 my-frame-width 和 my-frame-height)。我更喜欢这种方法,因为它更直接。但是,这当然是见仁见智的问题。这里还有更多information on cons and list 供将来参考。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-28
      • 1970-01-01
      • 1970-01-01
      • 2014-11-22
      相关资源
      最近更新 更多