调用延迟序列的计数时出现ArityException

时间:2018-12-16 11:37:59

标签: clojure

我写了下面的函数来确定两个字符串是否恰好differing-char-no个字符位置不同。

(defn differ-by
    [id1 id2 differing-char-no]
    (let [zipped-ids (map vector (seq id1) (seq id2))
          differing-char-positions (filter #(not= %1 %2) zipped-ids)]
        (= differing-char-no (count differing-char-positions))))

但是,该函数在调用时会产生ArityException。异常来自count函数调用,并说Wrong number of args (1) passed to: ...

通过调试代码,我发现differing-char-positionszipped-ids都是惰性序列,尚未实现。但是,评估(count zipped-ids)可以立即正常工作,但是(count differring-char-positions)仅在调用(count zipped-ids)之后(即在实现zipped-ids之后)才有效。有人可以解释这种行为吗?为什么这些惰性序列的行为会有所不同?

1 个答案:

答案 0 :(得分:0)

zipped-ids产生一个向量序列,因此过滤器函数必须接受一个参数:

(filter (fn [[a b]] (not= a b)) (map vector (seq [1 2 3]) (seq '(:a :b :c))))

但是有更好的方法:

(filter (partial apply not=) (map vector (seq [1 2 3]) (seq '(1 :b :c))))