The while loop in Clojure
Overview
What is a loop?
A loop repeatedly executes a code block until a condition is satisfied.
What is a 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.
Syntax
(while(expression)
(do
codeblock))
Code example
(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)
Code explanation
-
Line 5: We create a function to demonstrate the
whileloop. -
Line 6: We define a variable
ywith theatomkeyword, so that the variable can be changed. -
Line 7: We declare the
whileloop with a condition that will continue running as long asyis less than 9. -
Line 8: The
doblock 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 ofy. -
Line 11: We call the
loopingfunction that we created earlier.