LoginSignup
1
1

More than 5 years have passed since last update.

使えるマクロ: シェル引数を変数にバインド

Posted at

こういうのこそマクロの使い道。

(defmacro with-boolean-options (bindings before after &body body)
  (assert (typep before 'symbol))
  (assert (typep after 'symbol))
  `(let ((,after ,before))
     (let ,(mapcar
            (lambda (bind)
              (ematch bind
                ((list (and var (type symbol))
                       (and str (type string)))
                 `(,var
                   (prog1
                     (if (member ,str ,after :test #'string=) t nil)
                     (setf ,after (remove ,str ,after :test #'string=)))))))
            bindings)
       ,@body)))


(defun main ()
  (print sb-ext:*posix-argv*)
  (match sb-ext:*posix-argv*
    ((list* _ rest)
     (with-boolean-options ((*invert* "--invert")
                            (*ignore-first* "--ignore-first")
                            (*block* "--block")) rest rest
       (apply #'output-to-csv rest)))))

;;;; 展開結果
(LET ((REST REST))
  (LET ((*INVERT*
         (PROG1
             (IF (MEMBER "--invert" REST :TEST #'STRING=)
                 T
                 NIL)
           (SETF REST (REMOVE "--invert" REST :TEST #'STRING=))))
        (*IGNORE-FIRST*
         (PROG1
             (IF (MEMBER "--ignore-first" REST :TEST #'STRING=)
                 T
                 NIL)
           (SETF REST (REMOVE "--ignore-first" REST :TEST #'STRING=))))
        (*BLOCK*
         (PROG1
             (IF (MEMBER "--block" REST :TEST #'STRING=)
                 T
                 NIL)
           (SETF REST (REMOVE "--block" REST :TEST #'STRING=)))))
    (APPLY #'OUTPUT-TO-CSV REST)))

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1