【问题标题】:Clojure Spec on a vararg function可变参数函数上的 Clojure 规范
【发布时间】:2016-07-07 18:50:38
【问题描述】:

我正在尝试为合并函数编写规范,该函数将函数和映射作为输入并使用函数来解决冲突。但是我为该函数编写的规范失败了。我正在尝试弄清楚如何为这些函数编写规范。

下面是代码sn-p。

(require '[clojure.spec.test :as stest])
(require '[clojure.spec :as spec])

(defn deep-merge-with [func & maps] 
  (let [par-func (partial deep-merge-with func)] 
    (if (every? map? maps) 
        (apply merge-with par-func maps) 
        (apply func maps))))

(spec/fdef deep-merge-with
           :args (spec/cat :func (spec/fspec :args (spec/cat :maps (spec/* map?))
                                             :ret map?)
                           :maps (spec/cat :maps (spec/* map?)))
           :ret map?)

(stest/instrument `deep-merge-with)

(deep-merge-with (fn [f s] s) {:a 1} {:a 2})

我得到的规范错误是:

clojure.lang.ExceptionInfo: Call to #'boot.user/deep-merge-with did not conform to spec:
    In: [0] val: () fails at: [:args :func] predicate: (apply fn),  Wrong number of args (0) passed to: user/eval22001/fn--22002
                                :clojure.spec/args  (#function[boot.user/eval22001/fn--22002] {:a 1} {:a 2})

【问题讨论】:

    标签: clojure specifications clojure.spec


    【解决方案1】:

    在您的 [:args :func] 规范中:

    (spec/fspec :args (spec/cat :maps (spec/* map?)) :ret map?)
    

    您是说该函数必须接受任意数量的地图作为参数并返回一个地图。但是您传递给deep-merge-with 的函数不符合该规范:

    (fn [f s] s)
    

    这个函数只接受 两个 参数,而不是任意数量的地图。

    【讨论】:

    • (deep-merge-with (fn [& maps] (last maps)) {:a 1} {:a 2}) 也不起作用,我们如何在 (fn [f s] s) 上执行规范以使规范恰好采用两个参数。
    • 非常感谢,它帮助我调试了问题,我很愚蠢,我的函数输入不是映射,在深度合并过程中,当调用 merge-with 函数时,它实际上传递了冲突的值为功能。所以像这样的规范将起作用(spec/fdef deep-merge-with :args (spec/cat :func (spec/fspec :args (spec/cat :m1 ::spec/any :m2 ::spec/any) :ret ::spec/any) :maps (spec/cat :maps (spec/* ::spec/any))) :ret map?)
    • 我不知道如何将您的答案标记为正确,请帮助
    • @Vijay 您应该可以点击我帖子旁边的向上/向下投票按钮下方的灰色箭头来接受我的回答。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-15
    • 1970-01-01
    • 1970-01-01
    • 2016-11-25
    • 1970-01-01
    相关资源
    最近更新 更多