【问题标题】:Clojure assert not nil at compile time?Clojure 在编译时断言不为零?
【发布时间】:2014-03-15 04:01:17
【问题描述】:

我们可以在 Clojure 中看到 a way to use design by contract to check that arguments 到 Clojure 中的函数在运行时不是零。

(defn constrained-fn [ x]
  {:pre  [(not (nil? x))]}
  x)
(constrained-fn nil)
=> AssertionError Assert failed: (not (nil? x))  ...../constrained-fn (form-init5503436370123861447.clj:1)

我们可以在 Clojure 中看到check the type of an expression at compile time 的方法

(defmacro typeof 
  ([expression]
    (:class (expression-info expression)))

(defmacro primitive? 
  ([expression]
    (:primitive? (expression-info expression))))

这是我对基于compile-time macros in Clojure的问题的看法:

(defmacro compile-time-nil-check [x] (assert (not (nil? x))))
(def my-nullable nil)
(compile-time-nil-check my-nullable)

我的问题是 - 有没有办法在 Clojure 的编译时检查“常量”是否不为零?

(我意识到这个问题可能看起来微不足道——我想用它作为后续问题的构建块,以解决有关 Clojure 中编译时类型检查的后续问题)。

【问题讨论】:

    标签: macros clojure compile-time


    【解决方案1】:

    如果“常量”是指存储在全局 var 中的东西

    (def my-nullable nil)
    

    可以在编译时解决,那么:

    (defmacro compile-time-var-nil-check [x] 
      (let [x @(resolve x)] 
        (assert (not (nil? x)))))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-26
      • 2011-04-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多