Lisp - dotimes 構造



dotimes 構造允許迴圈執行固定次數的迭代。

語法

(dotimes (n range)
   statement1
   ...
)
  • n - 初始值,設定為 0。

  • range - 迴圈結束前到最後一個值。

  • statement1 - 要執行的語句。

示例 - 數字的平方

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

main.lisp

; perform a dotimes operation on list of numbers
(dotimes (n 11)
   (print n) (prin1 (* n n)) ; print n and square of n
)

輸出

當單擊“執行”按鈕或鍵入 Ctrl+E 時,LISP 會立即執行它,並返回以下結果 -

0 0
1 1
2 4
3 9
4 16
5 25
6 36
7 49
8 64
9 81
10 100

示例 - 數字的立方

更新原始碼檔案並命名為 main.lisp,並在其中鍵入以下程式碼 -

main.lisp

; perform a dotimes operation on list of numbers
(dotimes (n 11)
   (print n) (prin1 (* n(* n n))) ; print n and qube of n
)

輸出

當單擊“執行”按鈕或鍵入 Ctrl+E 時,LISP 會立即執行它,並返回以下結果 -

0 0
1 1
2 8
3 27
4 64
5 125
6 216
7 343
8 512
9 729
10 1000

示例 - 一個數字的雙倍

更新原始碼檔案並命名為 main.lisp,並在其中鍵入以下程式碼 -

main.lisp

; perform a dotimes operation on list of numbers
(dotimes (n 11)
   (print n) (prin1 (+ n n)); print n and double of n
)

輸出

當單擊“執行”按鈕或鍵入 Ctrl+E 時,LISP 會立即執行它,並返回以下結果 -

0 0
1 2
2 4
3 6
4 8
5 10
6 12
7 14
8 16
9 18
10 20
lisp_loops.htm
廣告