有什么方法可以在 Common Lisp 中将布尔值解析为整数?

Is there any way to parse from boolean to integer in Common Lisp?

我正在寻找 Common Lisp 中的一些内置函数或运算符,当输入为 false 布尔表达式时 return '0',当输入为 true 时为 '1'。一个例子是:

(setq a 3)
(setq b (+ (bool-to-int (< 0 a)) 2)
(print "b should be 1 + 2 = 3")

有没有办法在不定义自定义函数的情况下使用 Common Lisp 做到这一点?

您可以在需要将布尔表达式映射到 [0, 1] 的任何地方编写 (if <exp> 1 0)。没有内置的表格可以完全按照你写的去做。

也许不是一个非常优雅的解决方案,但您可以创建一个散列 table,例如,

(setf *ht-bool-to-int* (make-hash-table))
(setf (gethash nil *ht-bool-to-int*) 0)
(setf (gethash t *ht-bool-to-int*) 1)
(defun bool-to-int (b)
     (gethash (not (not b)) *ht-bool-to-int*))

(编辑:不嵌套随机表达式,其计算结果为真但不直接注册哈希 table) 然后你可以在不使用内置 if 的情况下实现你自己的“if”版本,即

(defmacro my-if (condition then-clause else-clause)
  (let ((ev (gensym)))
     `(let ((,ev (vector (quote ,else-clause) (quote ,then-clause))))
          (eval (aref ,ev (bool-to-int ,condition))))))

事后思考:散列 table 是使用 if 实现的吗?