dotimes 宏 ¶dotimes 宏与 dolist 类似,
区别是它会循环指定次数。
dotimes 的第一个参数在每次循环时
会依次被赋值为 0、1、2……
你需要提供第二个参数的值,即宏的循环次数。
例如,下面的代码将从 0 到 3(不含 3)的数字 依次绑定到第一个参数 number, 然后构造包含这三个数字的列表。 (第一个数字是 0,第二个是 1,第三个是 2; 从 0 开始,一共三个数字。)
(let (value) ; otherwise a value is a void variable
(dotimes (number 3)
(setq value (cons number value)))
value)
⇒ (2 1 0)
使用 dotimes 的方式是对某个表达式
重复操作 number 次,然后返回结果,
可以是列表或原子。
下面是一个使用 dotimes 实现的 defun 示例,
用于计算三角形石子总数。
(defun triangle-using-dotimes (number-of-rows)
"Using `dotimes', add up the number of pebbles in a triangle."
(let ((total 0)) ; otherwise a total is a void variable
(dotimes (number number-of-rows)
(setq total (+ total (1+ number))))
total))
(triangle-using-dotimes 4)