Trivial doctests in Common Lisp

The pros and cons of doctests have been discussed elsewhere so I won’t enter that debate here.

I was told it was trivial to roll your own doctest suite in Common Lisp. I have done that and it is easy indeed but I have included the code in incf-cl for those who would like to use it right away.

Here’s an example:

  (defpackage :test
    (:use :common-lisp :incf-cl)
    (:export :factorial))

  (in-package :test)

  (defun factorial (n &optional (acc 1))
    "Returns the factorial of N, where N is an integer >= 0.

    Examples:

    TEST> (assemble (factorial n) (<- n (range 1 5)))
    (1 2 6 24 120)

    TEST> (factorial 450/15)
    265252859812191058636308480000000

    TEST> (signals-p arithmetic-error (factorial -1))
    T

    TEST> (signals-p type-error (factorial 30.1))
    T

    TEST> (factorial 0)
    1"
    (declare (type integer n))

    (cond
      ((minusp n) (error 'arithmetic-error))
      ((/= n (floor n)) (error 'type-error)))

    (if (= n 0)
        acc
        (factorial (1- n) (* n acc))))
CL-USER> (doctest :test)
.....T

About this entry