Skip to content

Instantly share code, notes, and snippets.

@arademaker
Last active February 9, 2020 18:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arademaker/50aa74e490bf2160547cb212c9a1bf05 to your computer and use it in GitHub Desktop.
Save arademaker/50aa74e490bf2160547cb212c9a1bf05 to your computer and use it in GitHub Desktop.
(defmacro with-open-files (args &rest body)
(let ((res `(progn ,@body)))
(reduce (lambda (acc e) `(with-open-file (,@e) ,acc)) args
:initial-value res)))
(defmacro with-open-files-1 (args &rest body)
(let ((res `(progn ,@body)))
(dolist (a (reverse args) res)
(setf res `(with-open-file (,@a)
,res)))))
;; testing
(with-open-files ((in filename-in :direction :input)
(log filename-log :direction :ouput :if-exists :append)
(out filename-out :direction :ouput :if-exists :supersede))
(format out "ads")
(format out "ads"))
;; I want
(with-open-file (out filename-out :direction :ouput :if-exists
:supersede)
(with-open-file (log filename-log :direction :ouput :if-exists
:append)
(with-open-file (in filename-in :direction :input)
(format out "ads")
(format out "ads")))))
;; I got
(with-open-file (out filename-out :direction :ouput :if-exists
:supersede)
(with-open-file (log filename-log :direction :ouput :if-exists
:append)
(with-open-file (in filename-in :direction :input)
(progn (format out "ads")
(format out "ads")))))
@arademaker
Copy link
Author

arademaker commented Feb 9, 2020

My final version is

(defmacro with-open-files (args &body body)
  (case (length args)
    ((0)
     `(progn ,@body))
    ((1)
     `(with-open-file ,(first args) ,@body))
    (t `(with-open-file ,(first args)
	  (with-open-files
	      ,(rest args) ,@body)))))

@PuercoPop
Copy link

PuercoPop commented Feb 9, 2020

There is no need to distinguish having one spec left from having many. Only the bottom case is important. One can simplify the macro to:

(defmacro with-open-files (args &body body)
  (if args
      `(with-open-file ,(first args)
         (with-open-files
             ,(rest args) ,@body))
      `(progn ,@body)))

Btw the nest macro is designed as a more general solution to this situation. I prefer your solution though.
https://github.com/ruricolist/serapeum/blob/master/REFERENCE.md#nest-rest-things

@arademaker
Copy link
Author

Indeed, thank you for the improvement. It would bd nice to have it in serapeum!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment