Hacker Newsnew | past | comments | ask | show | jobs | submitlogin
Clojure macros continue to surprise me (tonsky.me)
10 points by packetlost on July 22, 2024 | hide | past | favorite | 1 comment


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))))




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: