1 comment

[ 4.3 ms ] story [ 7.9 ms ] thread
An alternative that doesn't need to involve macros is to write the example forms in their own file and use a load function that keeps, say, the text and form along with the evaluation of each form. In Common Lisp:

  (defclass annotated-evaluation ()
    ((text :initarg :text :reader ev-text)
     (form :initarg :form :reader ev-form)
     (values :initarg :values :reader ev-values)))
  
  (defun load-file (filename)
    (let ((content (alexandria:read-file-into-string filename))
          (pos 0)
          (eof (make-symbol "EOF")))
      (loop for (form end-pos) = (multiple-value-list
                                  (read-from-string content nil eof :start pos))
            until (eq form eof)
            collect (make-instance 'annotated-evaluation
                                   :text (string-trim '(#\Newline #\Space #\Tab)
                                                      (subseq content pos end-pos))
                                   :form form
                                   :values (multiple-value-list (eval form)))
            do (setf pos end-pos))))