有没有一种方法可以调整常见的lisp点宏,以免从零开始,而是从其他数字(例如1)开始?

发布于 2025-01-31 06:05:28 字数 847 浏览 2 评论 0原文

我正在使用Emacs,Slime和SBCL。

dotimes的默认使用是:

CL-USER> (defun my-dotimes (n)
           (dotimes (i n)
             (format t "~s ~%" i)))

生成:

CL-USER> (my-dotimes 10)
0 
1 
2 
3 
4 
5 
6 
7 
8 
9 
NIL

我希望该函数可以从一个开始计数。我可以通过它来更改:

CL-USER> (defun my-new-dotimes (n)
           (dotimes (i (- n 1))
             (format t "~s ~%" (+ i 1))))
MY-NEW-DOTIMES
CL-USER> (my-new-dotimes 10)
1 
2 
3 
4 
5 
6 
7 
8 
9 
NIL

但是,它并不像一个优雅的解决方案。

官方文档提到neclare可能性。但是我不确定如何使用它。

有更好的方法吗?

I am using Emacs, Slime, and SBCL.

The default use of dotimes is:

CL-USER> (defun my-dotimes (n)
           (dotimes (i n)
             (format t "~s ~%" i)))

Which generates:

CL-USER> (my-dotimes 10)
0 
1 
2 
3 
4 
5 
6 
7 
8 
9 
NIL

I wish the function could start counting from one. I can change it with:

CL-USER> (defun my-new-dotimes (n)
           (dotimes (i (- n 1))
             (format t "~s ~%" (+ i 1))))
MY-NEW-DOTIMES
CL-USER> (my-new-dotimes 10)
1 
2 
3 
4 
5 
6 
7 
8 
9 
NIL

But, it does not feel like an elegant solution.

The official documentation mentions a declare possibility. But I am not sure how to use it.

Is there a better way to do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

臻嫒无言 2025-02-07 06:05:29

不,没有办法使用dotimes来做到这一点。如果您需要一个从1计算的宏,则使用loopdo或编写一个。

使用

(do ((i 1 (1+ i))
    ((> i 10))
  ...)

No, there is no way to do that with dotimes. If you want a macro which counts from 1, either use loop or do or write one.

Using do:

(do ((i 1 (1+ i))
    ((> i 10))
  ...)
━╋う一瞬間旳綻放 2025-02-07 06:05:29
CL-USER 15 > (defmacro dotimes-start ((var n start
                                       &optional (result nil))
                                      &body body)
               `(loop for ,var from ,start
                      repeat ,n
                      do (progn ,@body)
                      finally (return ,result)))
DOTIMES-START

CL-USER 16 > (dotimes-start (i 10 2) (print i))

2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
NIL

CL-USER 17 > (let ((s 0))
               (dotimes-start (i 10 3 s)
                 (incf s (sin i))))
-1.8761432
CL-USER 15 > (defmacro dotimes-start ((var n start
                                       &optional (result nil))
                                      &body body)
               `(loop for ,var from ,start
                      repeat ,n
                      do (progn ,@body)
                      finally (return ,result)))
DOTIMES-START

CL-USER 16 > (dotimes-start (i 10 2) (print i))

2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
NIL

CL-USER 17 > (let ((s 0))
               (dotimes-start (i 10 3 s)
                 (incf s (sin i))))
-1.8761432
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文