【问题标题】:Customized conditional assertion error message in Clojure?Clojure 中的自定义条件断言错误消息?
【发布时间】:2014-12-19 10:03:22
【问题描述】:

假设我想提醒用户输入类型错误,例如

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

是否可以发出“仅正数”消息,而不是诸如断言失败之类的消息?

【问题讨论】:

    标签: clojure


    【解决方案1】:

    您可以使用dire 执行此操作。你应该看看它对preconditions 的支持。

    【讨论】:

      【解决方案2】:

      如果你不想依赖外部库,clojure 的(assert) 支持可选消息。

      缺点是,您将失去:pre 的可读性,并且必须将结果保存在一个中间变量中以供:post 检查(或将其包装在一些宏魔术中)。

      简单示例:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-03-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多