1

我正在玩功能规范,我想知道是否可以使用它来模拟编译类型检查?宏是在编译时评估的,所以如果我可以这样做:

(: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))
4

1 回答 1

-1

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

在生产中检测函数也不是一个好主意,因为它确实会降低其性能。仅在测试中使用它们。请参见下面的示例:

(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
于 2017-12-15T09:34:57.040 回答