LISP 中的循环构造
在本文中,我们将讨论循环构造。此 Construct 用于迭代数据,直到找到返回语句。然后它将停止迭代并返回结果。
语法:
(loop (statements)
condition
return
)
在哪里,
- 循环是关键字
- 语句用于迭代循环
- condition用于指定条件以便循环停止迭代
- return语句用于返回结果
示例:迭代元素的 LISP 程序
Lisp
;define a variable and set to 1
(setq var 1)
;start the loop
(loop
;increment value by 2 each time
;till value is less than 30
(setq var (+ var 2))
;display
(write var)
(terpri)
;condition for value is less than 30
(when (> var 30) (return var))
)
Lisp
;define a variable and set to 100
(setq var 100)
;start the loop
(loop
;decrement value by 10 each time
;till value is less than 30
(setq var (- var 10))
;display
(write var)
(terpri)
;condition for value is less than 30
(when (< var 30) (return var))
)
输出:
3
5
7
9
11
13
15
17
19
21
23
25
27
29
31
示例 2:
语言
;define a variable and set to 100
(setq var 100)
;start the loop
(loop
;decrement value by 10 each time
;till value is less than 30
(setq var (- var 10))
;display
(write var)
(terpri)
;condition for value is less than 30
(when (< var 30) (return var))
)
输出:
90
80
70
60
50
40
30
20