【问题标题】:Can one use the "it" command outside of a loop in Lisp?可以在 Lisp 的循环之外使用“it”命令吗?
【发布时间】:2013-07-19 17:12:47
【问题描述】:

我知道在 Lisp 循环中,可以使用特殊变量“it”,就像 Gigamonkeys 的这个例子:

(loop for key in some-list when (gethash key some-hash) collect it)

我想知道除了使用 let 显式存储它之外,循环之外是否还有任何等效概念,如下所示:

(let ((result (foo input)))
     (when result (push result acc)))

我可以使用 let,但我只是好奇是否有一些语法糖可以使我的代码更简洁。

【问题讨论】:

    标签: lisp common-lisp syntactic-sugar


    【解决方案1】:

    lisp-y 的答案是,谁在乎是否没有语法,只需添加您自己的。

    (defmacro awhen (test &body body)
        `(let ((it ,test))
              (when it ,@body)))
    

    然后使用它

    (awhen (expensive-computation)
           (format t "~a~%" it))
    

    这类宏通常以“a”为前缀,表示照应。有关 Paul Graham 在 On Lisp 中的示例,请参阅 aif

    【讨论】:

    • 谢谢!完全忘记了 lisp 的细微之处。
    • 看到了吗?宏非常流畅,即使您使用其中之一,您实际上也可以忘记它们的存在,例如loop
    • 还有一个包含许多正常控制结构的照应版本的包。它被称为照应。见:common-lisp.net/project/anaphora
    猜你喜欢
    • 2013-05-09
    • 1970-01-01
    • 1970-01-01
    • 2020-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多