LISP 中的 Dolist 构造
Common LISP 中的 DoList 是一个循环语句,用于迭代列表中的元素。
句法:
(dolist input_list)
statements...
)
这里,
- input_list包含迭代的元素列表。
- 语句存在于循环中。
示例 1: LISP 程序以迭代从 1 到 5 的元素列表。
Lisp
;create a dolist of 1 to 5 elements in a list
(dolist (n '(1 2 3 4 5 ))
;iterate elements
(format t "~% List of elements: ~d " n)
)
Lisp
;create a dolist of 1 to 5 elements in a list
(dolist (n '(1 2 3 4 5 ))
;iterate elements to find sum of each element
(format t "~% sum of element: ~d " (+ n n))
(terpri)
;iterate elements to find square of each element
(format t "~% square of element: ~d " (* n n))
)
输出:
List of elements: 1
List of elements: 2
List of elements: 3
List of elements: 4
List of elements: 5
示例 2: LISP 程序通过迭代找到每个元素的平方和总和。
Lisp
;create a dolist of 1 to 5 elements in a list
(dolist (n '(1 2 3 4 5 ))
;iterate elements to find sum of each element
(format t "~% sum of element: ~d " (+ n n))
(terpri)
;iterate elements to find square of each element
(format t "~% square of element: ~d " (* n n))
)
输出:
sum of element: 2
square of element: 1
sum of element: 4
square of element: 4
sum of element: 6
square of element: 9
sum of element: 8
square of element: 16
sum of element: 10
square of element: 25