【问题标题】:Clojure :pre report failing value when destructuringClojure:解构时预先报告失败的值
【发布时间】:2016-01-22 16:59:57
【问题描述】:

按照这个SO post,我想在我的函数中打印前置条件的值。但是在以下情况下它对我来说失败了(可能是解构):

我有一个dir? 辅助函数(可以跳过这个):

(defn dir? [s]
  "returns true if the string passed is is an existing directory"
  (->> (clojure.java.io/file s)
       ((juxt #(.exists %) #(.isDirectory %)))
       (every? true?)))

它工作得很好,并且使用 is 宏,我收到了一些很好的错误消息,我可以看到测试和传递的参数:

(is (dir? (io/file "resources/static"))) ;; => true

(is (dir? (io/file "resources/statice"))) ;; typo, error below

clojure.lang.PersistentList$EmptyList@1 中的失败 (boot.user4515592986834245937.clj:86)预期:(dir?(io /文件 “资源/静态”))实际:(不是(dir?#object [java.io.File 0x6730a420 "资源/静态"]))

但是,当尝试在前提条件:pre 中使用它时,我收到了一个丑陋的错误:

(defn make-something
  [&{:keys [dir]
     :or {dir "default-dir"}}]
  {:pre [(is (dir? (clojure.java.io/file dir)))]}
  ;;... do something with these
 )

(make-something :dir "resources/statices") ;; doesn't exist

clojure.lang.Compiler$CompilerException: java.lang.AssertionError: 断言失败: (is (dir? (io/file dir))), 编译:(boot.user4515592986834245937.clj:80:12) java.lang.AssertionError: Assert failed: (is (dir? (io/file dir)))

我怎样才能在我的函数中得到一个很好的错误消息,就像上面的一样?

如果重要的话,我使用的是 Clojure 1.7。

【问题讨论】:

标签: error-handling clojure preconditions


【解决方案1】:

您需要检查您的代码(dir? 函数)。以下 sn-p 对我有用:

(require '[clojure.java.io :as io])

(defn dir? [s]
  (let [dir (io/file s)]
    (and (.exists dir)
         (.isDirectory dir))))

(defn make-something
  [& {:keys [dir] :or {dir "default-dir"}}]
  {:pre [(is (dir? dir))]}
  (println dir))

(make-something :dir "/tmp")
out => /tmp
ret => nil

(make-something :dir "/xxxx")
FAIL in clojure.lang.PersistentList$EmptyList@1 (form-init3332271312167175068.clj:1)
expected: (dir? dir)
actual: (not (dir? "/xxxx"))

AssertionError Assert failed: (is (dir? dir))  user/make-sth (form-init3332271312167175068.clj:1)

【讨论】:

  • 这是因为我在 Arthur 的评论之后手动编辑了代码。您的代码现在可以在我的 REPL 中运行,所以我接受了您的答案(虽然 Clojure 1.8 - 我没有像我原来的问题那样使用 1.7 进行测试)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-02
相关资源
最近更新 更多