Lisp - 迴圈構造



loop 構造是 LISP 提供的最簡單的迭代形式。它的最簡單形式允許你重複執行一些語句,直到找到 return 語句。

它具有以下語法 −

(loop (s-expressions))

示例

建立一個名為 main.lisp 的新原始碼檔案,並在其中鍵入以下程式碼。

main.lisp

; set a as 10
(setq a 10)
; start a loop
(loop 
   ; increment a by 1
   (setq a (+ a 1))
   ; print a
   (write a)
   ; terminate printing
   (terpri)
   ; return a if a becomes greater than 17
   (when (> a 17) (return a))
)

輸出

執行程式碼時,將返回以下結果 −

11
12
13
14
15
16
17
18

請注意,如果沒有 return 語句,loop 宏將產生一個無限迴圈。

示例

更新名為 main.lisp 的原始碼檔案,並在其中鍵入以下程式碼。在此示例中,我們按降序列印數字。

main.lisp

; set a as 20
(setq a 20)
; start the loop
(loop 
   ; decrement a by 1
   (setq a (- a 1))
   ; print a
   (write a)
   ; terminate printing
   (terpri)
   ; if a becomes less than 10, return the same.
   (when (< a 10) (return a))
)

輸出

執行程式碼時,將返回以下結果 −

19
18
17
16
15
14
13
12
11
10
9
lisp_loops.htm
廣告
© . All rights reserved.