11

I was to understanding that Clojure's *assert* variable could be used to turn off assertions, but nothing I do seems to works.

(defn foo [a]
  {:pre [(pos? a)]}
  (assert (even? a))
  [a])

(binding [*assert* false]
  (foo 1))
!! exception

(binding [*assert* false]
  (foo -2))
!! exception

Even to binding false when defining has same problems:

(binding [*assert* false]
  (defn bar [a]
    {:pre [(pos? a)]}
    (assert (even? a))
    [a]))

(bar 1)
!! execption

And then even to setting the variable direct does not working.

*assert*
is true

(alter-var-root (var *assert*) not)
*assert*
is still true

and

(var-set (var *assert*) false)
*assert*
is still true

So now I am not understanding what to do. I am confused.

Thank you.

4

2 回答 2

14

*assert*是编译时变量,而不是运行时变量。它应该用作set!顶级语句,而不是绑定(当然,除非您eval在绑定内部调用)。

于 2011-02-02T14:28:16.487 回答
4

assert 是以某种方式定义的宏,*assert*会影响它在扩展时的行为。

如果您尝试此代码,它将按预期工作:

(binding [*assert* false]
   (eval '(assert false))
)

并且您使用var-set的示例也应该有效:

(var-set (var *assert*) false)
(assert false)
于 2011-02-02T14:15:51.567 回答