Lisp:带有&可选和&body的defmacro

asb*_*asb 5 lisp sbcl common-lisp

我写了一个快速但肮脏的宏来计时 Lisp 代码。然而,我现在面临的问题是我想在函数中包含一个可选的输出流。但是,我不知道&optional如何&bodydefmacro. 我寻找了一些例子,但只找到了那些defun我认为我理解的例子。我无法弄清楚为什么这对我来说失败了。任何提示:

(defmacro timeit (&optional (out-stream *standard-output*) (runs 1) &body body)
  "Note that this function may barf if you are depending on a single evaluation
  and choose runs to be greater than one. But I guess that will be the
  caller's mistake instead."
  (let ((start-time (gensym))
        (stop-time (gensym))
        (temp (gensym))
        (retval (gensym)))
    `(let ((,start-time (get-internal-run-time))
           (,retval (let ((,temp))
                      (dotimes (i ,runs ,temp)
                        (setf ,temp ,@body))))
           (,stop-time (get-internal-run-time)))
       (format ,out-stream
               "~CTime spent in expression over ~:d iterations: ~f seconds.~C"
               #\linefeed ,runs
               (/ (- ,stop-time ,start-time)
                  internal-time-units-per-second)
               #\linefeed)
       ,retval)))
Run Code Online (Sandbox Code Playgroud)

这就是我打算使用代码的方式:

(timeit (+ 1 1)) ; Vanilla call
(timeit *standard-output* (+ 1 1)) ; Log the output to stdout
(timeit *standard-output* 1000 (+ 1 1)) ; Time over a 1000 iterations.
Run Code Online (Sandbox Code Playgroud)

我认为从hyperspec中发现的这一点defmacro是类似的想法。

(defmacro mac2 (&optional (a 2 b) (c 3 d) &rest x) `'(,a ,b ,c ,d ,x)) =>  MAC2 
(mac2 6) =>  (6 T 3 NIL NIL) 
(mac2 6 3 8) =>  (6 T 3 T (8)) 
Run Code Online (Sandbox Code Playgroud)

编辑:关键字参数

上面显示的用法显然是有缺陷的。也许,这样更好:

(timeit (+ 1 1)) ; Vanilla call
(timeit :out-stream *standard-output* (+ 1 1)) ; Log the output to stdout
(timeit :out-stream *standard-output* :runs 1000 (+ 1 1)) ; Time over a 1000 iterations.
Run Code Online (Sandbox Code Playgroud)

谢谢。

Rai*_*wig 3

那应该如何运作?

应该如何检测第一个是可选流呢?

(timeit a)      ; is a the optional stream or an expression to time?
(timeit a b)    ; is a the optional stream or an expression to time?
(timeit a b c)  ; is a the optional stream or an expression to time?
Run Code Online (Sandbox Code Playgroud)

我会避免这样的宏参数列表。

通常我会更喜欢:

(with-timings ()
  a b c)
Run Code Online (Sandbox Code Playgroud)

和一个流

(with-timings (*standard-output*)
  a b c)
Run Code Online (Sandbox Code Playgroud)

第一个列表给出了可选参数。该列表本身不是可选的。

该宏应该更容易编写。

一般来说,可能不需要指定流:

(let ((*standard-output* some-stream))
  (timeit a b c))
Run Code Online (Sandbox Code Playgroud)

你可以实现你想要的,但我不会这样做:

(defmacro timeit (&rest args)
   (case (length args)
     (0 ...)
     (1 ...)
     (otherwise (destructuring-bind (stream &rest body) ...))))
Run Code Online (Sandbox Code Playgroud)

  • @asb:先不要编写宏。展示使用此类宏的代码的示例,找出它是否有意义,然后尝试编写宏来实现语法。您需要**首先**获取语法,然后**编写宏。现在你有了一个宏,我们必须猜测它会如何使用......对我来说,完全不清楚这样的参数列表是否有意义。 (3认同)