如何在elisp的“if”语句中编写多个语句?

81

在elisp中,有一个 "if" 语句,我希望能够执行许多不同的操作:

(if condition
    (do-something)
    (do-another-thing)
    ...)
然而,(do-another-thing) 只在 else 语句中执行。你如何指定需要执行的一组指令?例如:
(if condition
    (begin
        (do-something)
        (do-another-thing)
        ...))
2个回答

109

使用 progn:

(if condition
    (progn
        (do-something)
        (do-another-thing)))

请参考手册中的序列章节。


53

如果没有需要使用else的情况,使用以下代码可能更易读:

(when condition
    (do-something)
    (do-another-thing))

还有一个相反的情况

(unless (not condition)
    (do-something)
    (do-another-thing))

查看Emacs Lisp条件语句手册


3
就我个人而言,通常会遵循《Common Lisp The Language》建议中的惯例,在返回值不重要时使用whenunless(即它们仅用于产生副作用)。当返回值很重要时,我通常会使用andor。当有多个分支(无论返回值是否重要)时,我通常会使用ifcond - Drew

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接