gpt4 book ai didi

条件的 LISP 特殊形式

转载 作者:太空宇宙 更新时间:2023-11-03 18:49:07 25 4
gpt4 key购买 nike

我正在阅读 Peter Norvig 的书人工智能编程范式:Common LISP 中的案例研究,在关于条件的特殊形式的章节中,它说它们都可以被替换如果形式

(when test a b c) == (if test (progn a b c)) 
(unless test x y) == (if (not test) (progn x y)
(and a b c) == (if a (if b c))
(or a b c) == (if a a (if b b c))
(case a (b c) (t x)) == (if (eql a 'b) c x)

我不明白这是怎么回事,谁能给我解释一下?那cond形式呢,是不是也可以换成if形式呢?然后我可以用 if 形式创建一个宏函数来替换 whenunlessand 等吗? ..?

最佳答案

IF 是一个通用条件,它根据一个条件从两个分支中进行选择。当有两个以上的分支(ANDORCASE)或只有一个分支( 何时除非)。

COND也可以用IF来完成,例如:

(eval-when (:compile-toplevel :load-toplevel :execute)
(defun ifify-clauses (clauses)
(when clauses
(destructuring-bind (condition form) (first clauses)
`(if ,condition ,form ,(ifify-clauses (rest clauses)))))))

(defmacro if-cond (&body clauses)
(ifify-clauses clauses))

(macroexpand '(if-cond
((= 3 1) "foo")
((= 3 2) "bar")
((= 3 3) "quux")))
;=> (IF (= 3 1)
; "foo"
; (IF (= 3 2)
; "bar"
; (IF (= 3 3)
; "quux"
; NIL)))

关于条件的 LISP 特殊形式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36123901/

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