【问题标题】:Design By Contract LIbrary(ies) for Common Lisp?Common Lisp 的契约式设计库?
【发布时间】:2010-09-24 14:22:29
【问题描述】:

来自 Clojure 的背景,我被它的前置/后置条件作为合同设计的基础所吸引:

;; sqr.clj

(defn sqr [n]
  {:pre  [(not= 0 n) (number? n)]
   :post [(pos? %) (number? %)]}
  (* n n))

(sqr 10)
;=> 100

(sqr 0)
; Assertion error

Common Lisp 中是否有类似的 pre/post 功能和/或更全面的 Design by Contract 库?

谢谢

【问题讨论】:

    标签: clojure lisp common-lisp design-by-contract


    【解决方案1】:

    编写一个可以像这样使用的宏是相对简单的:

    (defun sqr (n)
      (with-dbc-checked
         (:pre  ((not (zerop n)) (numberp n))
          :post ((plusp %) (numberp %)))
        (* n n)))
    

    对于 CLOS 泛型函数,请参见此处:http://www.muc.de/~hoelzl/tools/dbc/dbc-intro.html

    顺便说一句,从这段代码可以看出,CL和Clojure之间可以进行零代码交换,而无需完全重写任何东西。

    【讨论】:

    • 这正是我要找的库。谢谢。
    【解决方案2】:

    你可以断言:

    (defun sqr (n)
      (assert (and
               (not (zerop n))
               (numberp n)))
      (* n n))
    

    不确切知道帖子部分要做什么。 :)

    【讨论】:

      猜你喜欢
      • 2011-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-15
      相关资源
      最近更新 更多