gpt4 book ai didi

error-handling - 克洛尤尔 :pre report failing value when destructuring

转载 作者:行者123 更新时间:2023-12-01 08:36:57 24 4
gpt4 key购买 nike

关注此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

FAIL in clojure.lang.PersistentList$EmptyList@1 (boot.user4515592986834245937.clj:86) expected: (dir? (io/file "resources/statice")) actual: (not (dir? #object[java.io.File 0x6730a420 "resources/statice"]))

但是,当尝试在前提条件 :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: Assert failed: (is (dir? (io/file dir))), compiling:(boot.user4515592986834245937.clj:80:12) java.lang.AssertionError: Assert failed: (is (dir? (io/file dir)))

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

以防万一,我使用的是 Clojure 1.7。

最佳答案

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

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

关于error-handling - 克洛尤尔 :pre report failing value when destructuring,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34952110/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com