gpt4 book ai didi

emacs - 如何在 ELisp 中创建命名参数?

转载 作者:行者123 更新时间:2023-12-04 01:22:52 24 4
gpt4 key购买 nike

我想,由于 Emacs Lisp 和 Common Lisp 在语法上看起来如此密切相关,我可以按照我在 RosettaCode 上找到的示例代码进行操作。 ,但事实证明我错了。

有问题的代码如下所示:

(defun print-name (&key first (last "?"))
(princ last)
(when first
(princ ", ")
(princ first))
(values))

根据 RosettaCode,它应该执行以下操作:
> (print-name)
?
> (print-name :first "John")
?, John
> (print-name :last "Doe")
Doe
> (print-name :first "John" :last "Doe")
Doe, John

现在,事情是这样的;每当我尝试在我的 ELisp 解释器中运行该函数时,都会收到以下错误:
*** Eval error ***  Wrong number of arguments: (lambda (&key first (last "?")) (princ la\
st) (if first (progn (princ ", ") (princ first))) (values)), 0

我在 lisp 中的例行程序不足以知道这应该是什么意思,并且没有多少谷歌搜索让我更接近答案。

那么在 Emacs Lisp 中这样做的正确方法是什么?

最佳答案

由于 Emacs Lisp 不直接支持关键字参数,因此您需要使用 cl-defun 模拟这些参数。就像在另一个答案中一样,或者通过将参数解析为 plist:

(defun print-name (&rest args)
(let ((first (plist-get args :first))
(last (or (plist-get args :last) "?")))
(princ last)
(when first
(princ ", ")
(princ first))))
&rest args告诉 Emacs 将所有函数参数放入一个列表中。 plist-get从属性列表中提取一个值,即格式为 (key1 value1 key2 value2 …) 的列表.实际上,plist 是扁平化的 alist。

这让您可以调用 print-name就像你的问题一样:
> (print-name)
?
> (print-name :first "John")
?, John
> (print-name :last "Doe")
Doe
> (print-name :first "John" :last "Doe")
Doe, John

关于emacs - 如何在 ELisp 中创建命名参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26102889/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com