简体   繁体   中英

Customized conditional assertion error message in Clojure?

Suppose I want alert the user the input type is wrong, for example

(defn my-sqrt [x] {:pre [(not (neg? x))]}        (Math/sqrt x))

Is it possible to issue a message "Positive number only.", instead of something like assert failed?

You can do this using dire . You should look at its support for preconditions .

If you don't want to rely on external libraries, clojure's (assert) supports an optional message.

The drawbacks are, you'll lose the readability of a :pre and will have to save the result in an intermediate variable for a :post check (or wrap it up in some macro magic).

Simple example:

(defn mysqrt [x]
  ;; preconditions
  (assert (pos? x) "Positive numbers only")
  (let [y (Math/sqrt x)]
    ;; postconditions
    (assert (number? y) "Some strange error happened")
    y))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM