# Elisp 04：迭代

``````(defun princ\' (x)
(princ x)
(princ "\n"))

(defun current-line ()
(buffer-substring (line-beginning-position) (line-end-position)))

(defun every-line ()
(if (= (point) (point-max))
(princ "")
(progn
(princ\' (current-line))
(forward-line 1)
(every-line))))

(progn
(find-file "foo.md")
(every-line))``````

Elisp 解释器在上述程序最后一个表达式 `(every-line)` 求值时，会转而对 `every-line` 函数定义里的每个表达式进行求值，但是当 Elisp 解释器在函数 `every-line` 的定义里又遇到了表达式 `(every-line)`，导致它不得不再次对 `every-line` 的定义里的每个表达式进行求值。该过程周而复始，在每一次反复对 `every-line` 的定义进行求值时，`princ\'` 会不断输出当前文本行，而 `forward-line` 又不断将插入点移动到下一行的开头。于是，上述程序便解决了读取当前缓冲区内的每一行文本并输出于终端这个问题。

`max-lisp-eval-depth` 是 Elisp 解释器的全局变量，它定义了函数递归深度。使用

``(princ\' max-lisp-eval-depth)``

``Lisp nesting exceeds ‘max-lisp-eval-depth’``

``````(while 逻辑表达式
一段程序)``````

``````(defun every-line ()
(while (< (point) (point-max))
(princ\' (current-line))
(forward-line 1)))``````

``````(defun reverse-list (x)
(let ((y '()))
(defun reverse-list\' (x)
(if (null x)
y
(progn
(setq y (cons (car x) y))
(reverse-list\' (cdr x)))))
(reverse-list\' x)))``````

``````(defun reverse-list (x)
(let ((y '()))
(while (not (null x))
(setq y (cons (car x) y))
(setq x (cdr x)))
y))``````

5.9k 声望
1.9k 粉丝
0 条评论