Design By Contract LIbrary(ies) for Common Lisp?
Asked Answered
E

2

9

Coming from a background in Clojure, I am taken with the potential that its pre-/post-conditions provide as a basis for design by contract:

;; sqr.clj

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

(sqr 10)
;=> 100

(sqr 0)
; Assertion error

Is there a similar pre/post capability in Common Lisp and/or a more comprehensive Design by Contract library available in the wild?

Thank you

Erkan answered 24/9, 2010 at 14:22 Comment(0)
P
8

it is relatively trivial to write a macro that can be used like this:

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

For CLOS generic functions, see here: http://www.muc.de/~hoelzl/tools/dbc/dbc-intro.html

Btw., from this code it can be seen that there is zero code exchange is possible between CL and Clojure, without rewriting anything completely.

Profound answered 24/9, 2010 at 14:36 Comment(1)
This is precisely the library that I was looking for. Thank you.Erkan
N
1

You can assert:

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

Don't know exactly what the post part is ment to do. :)

Nunciata answered 24/9, 2010 at 15:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.