clojure和规格的编译时间检查



我正在使用函数规格,我想知道是否可以使用它来模拟编译型检查?宏在编译时进行评估,因此,如果我可以做这样的事情:

(:require [clojure.spec.alpha :as s]
          [clojure.spec.test.alpha :as st])
(s/fdef divide
        :args (s/cat :x integer? :y integer?)
        :ret number?)
(defn divide [x y] (/ x y))
(st/instrument `divide)
(defmacro typed-divide [arg1 arg2]
  (eval `(divide ~arg1 ~arg2)))
;; this should fail to compile?
(defn typed-divide-by-foo [arg]
  (typed-divide arg :foo))

尽管宏系统可能会有一些技巧,但最好只为此编写单元测试。编译时错误非常模糊,并防止启动启动。相反,测试也处理异常,并在出现问题时收集不错的报告。

在生产中启动功能也不是一个好主意,因为它确实减慢了其性能。仅在测试中启动它们。请参阅下面的示例:

(ns project.tests
  (:require [clojure.test :refer :all]
            [project.code :refer [divide]]))
;; here, in test namespace, you instrument a function 
;; you'd like to test
(st/instrument `divide)
;; and then add a test
(deftest test-divide
  (is (= (divide 6 2) 3)))

现在,运行测试:

lein test

最新更新