我想if
用布尔逻辑和宏编写我自己的。我想出了以下实现:
(defmacro -if (condition if-true if-false)
"Implements `if` in terms of Boolean logic only"
`(or (and ,condition ,if-true)
(and (not ,condition) ,if-false)))
我在几个案例中手动测试了它,它按预期工作。但后来我写了一个简单的测试函数来执行一系列测试,得到了一个我仍然无法理解的结果。我写了这样的函数:
(defun -if-test ()
(let ((passed 0)
(test-format "TEST: ~50a ==> ~:[FAILURE~;SUCCESS~]~%")
(cases '((return-value (> 2 1) true)
(return-value (< 2 1) false)
(standard-output (> 2 1) "true")
(standard-output (< 2 1) "false"))))
(dolist (test-case cases)
(destructuring-bind (type test expected) test-case
(let ((result (case type
(return-value
(eq (-if test 'true 'false) expected))
(standard-output
(with-output-to-string (out)
(string= (-if test (print "true" out) (print "false" out)) expected)))
(otherwise (error "Unknown test type: ~a" type)))))
(when result (incf passed))
(format t test-format test-case result))))
(format t "Result: ~a/~a tests passed.~%" passed (length cases))))
当我运行测试时,我得到以下输出:
TEST: (RETURN-VALUE (> 2 1) TRUE) ==> SUCCESS
TEST: (RETURN-VALUE (< 2 1) FALSE) ==> FAILURE
TEST: (STANDARD-OUTPUT (> 2 1) true) ==> SUCCESS
TEST: (STANDARD-OUTPUT (< 2 1) false) ==> SUCCESS
Result: 3/4 tests passed.
NIL
第二个失败案例显然在手动运行时与作为此函数的一部分运行时给出不同的结果。我尝试使用 SLDB 对其进行调试,结果确实与独立执行不同。我怀疑我错过了一些关键的执行细节或类似的东西。有人可以向我解释这里发生了什么吗?帮助真的很感激。
PS 我的实现是 Clozure CL。