A loop
repeatedly executes a code block until a condition is satisfied.
while
loop in Clojure?A Clojure while
loop evaluates a conditional expression and if the condition returns true
, it executes the codes in the do
block until the conditional expression returns false
.
(while(expression)
(do
codeblock))
(ns clojure.examples.hello (:gen-class)) ;; This program displays Hello World (defn looping [] (def y (atom 1)) (while ( < @y 9 ) (do (println @y) (swap! y inc)))) (looping)
Line 5: We create a function to demonstrate the while
loop.
Line 6: We define a variable y
with the atom
keyword, so that the variable can be changed.
Line 7: We declare the while
loop with a condition that will continue running as long as y
is less than 9.
Line 8: The do
block is used to identify the code that will be repeated.
Line 9: We print the value of y
.
Line 10: We use swap!
to populate the changed values of y
.
Line 11: We call the looping
function that we created earlier.
RELATED TAGS
CONTRIBUTOR
View all Courses