【问题标题】:Is there any way to parse from boolean to integer in Common Lisp?有没有办法在 Common Lisp 中从布尔值解析为整数?
【发布时间】:2020-08-26 03:40:28
【问题描述】:
我正在寻找一些内置函数或 Common Lisp 中的一些运算符,当输入为假布尔表达式时将返回“0”,当输入为真时返回“1”。一个例子是:
(setq a 3)
(setq b (+ (bool-to-int (< 0 a)) 2)
(print "b should be 1 + 2 = 3")
有没有办法在不定义自定义函数的情况下使用 Common Lisp 做到这一点?
【问题讨论】:
标签:
int
boolean
lisp
common-lisp
【解决方案1】:
您可以在任何需要将布尔表达式映射到[0, 1] 的地方编写(if <exp> 1 0)。没有内置的表单可以完全按照你写的那样做。
【解决方案2】:
也许不是一个非常优雅的解决方案,但您可以创建一个哈希表,例如,
(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*))
(编辑:嵌套不用于将评估为真但不直接注册哈希表的随机表达式)
然后你可以不使用内置的 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))))))
事后思考:哈希表是用if实现的吗?