gpt4 book ai didi

Lisp: defmacro with &optional 和 &body

转载 作者:太空宇宙 更新时间:2023-11-03 18:40:07 24 4
gpt4 key购买 nike

我写了一个快速而肮脏的宏来为 lisp 代码计时。但是,我现在面临的问题是我想在函数中包含一个可选的输出流。但是,我不知道如何在 defmacro 中同时使用 &optional&body 参数。我查找了示例,但只找到了我认为我理解的 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)))

这就是我打算如何使用代码:

(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.

我想这个,从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))

编辑:关键字参数

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

(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.

谢谢。

最佳答案

这应该如何运作?

首先应该如何检测是可选流?

(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?

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

通常我更喜欢:

(with-timings ()
a b c)

还有流

(with-timings (*standard-output*)
a b c)

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

那个宏应该更容易写。

通常可能不需要指定流:

(let ((*standard-output* some-stream))
(timeit a b c))

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

(defmacro timeit (&rest args)
(case (length args)
(0 ...)
(1 ...)
(otherwise (destructuring-bind (stream &rest body) ...))))

关于Lisp: defmacro with &optional 和 &body,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27642626/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com