How can I get Clojure :pre & :post to report their failing value?

后端 未结 4 1560
粉色の甜心
粉色の甜心 2020-12-05 06:42
(defn string-to-string [s1] 
  {:pre  [(string? s1)]
   :post [(string? %)]}
  s1)

I like :pre and :post conditions, they allow me to figure out wh

4条回答
  •  Happy的楠姐
    2020-12-05 07:41

    @octopusgrabbus kind of hinted at this by proposing (try ... (catch ...)), and you mentioned that that might be too noisy, and is still wrapped in an assert. A simpler and less noisy variant of this would be a simple (or (condition-here) (throw-exception-with-custom-message)) syntax, like this:

    (defn string-to-string [s1] 
      {:pre  [(or (string? s1)
                  (throw (Exception. (format "Pre-condition failed; %s is not a string." s1))))]
       :post [(or (string? %)
                  (throw (Exception. (format "Post-condition failed; %s is not a string." %))))]}
      s1)
    

    This essentially lets you use pre- and post-conditions with custom error messages -- the pre- and post-conditions are still checked like they normally would be, but your custom exception is evaluated (and thus thrown) before the AssertionError can happen.

提交回复
热议问题