Clojure - dotimes語句



‘dotimes’ 語句用於執行某個語句 ‘x’ 次。

語法

以下是 doseq 語句的一般語法。

(dotimes (variable value)
   statement)

其中,value 必須是一個數字,表示迴圈需要迭代的次數。

以下是此迴圈的圖示。

Dotimes Statement

示例

以下是 ‘doseq’ 語句的示例。

(ns clojure.examples.hello
   (:gen-class))

;; This program displays Hello World
(defn Example []
   (dotimes [n 5]
   (println n)))
(Example)

在上面的例子中,我們使用 dotimes 語句重複執行 println 語句指定的次數。每次迭代還會遞增變數 n 的值。

輸出

以上程式碼產生以下輸出。

0
1
2
3
4
clojure_loops.htm
廣告
© . All rights reserved.