Concepts of Programming Languages

(Sean Pound) #1
8.3 Iterative Statements 367

for loop_variable in object:



  • loop body
    [else:

  • else clause]


The loop variable is assigned the value in the object, which is often a range, one
for each execution of the loop body. The else clause, when present, is executed
if the loop terminates normally.
Consider the following example:


for count in [2, 4, 6]:
print count


produces


2
4
6


For most simple counting loops in Python, the range function is used.
range takes one, two, or three parameters. The following examples demon-
strate the actions of range:


range(5) returns [0, 1, 2, 3, 4]
range(2, 7) returns [2, 3, 4, 5, 6]
range(0, 8, 2) returns [0, 2, 4, 6]


Note that range never returns the highest value in a given parameter range.


8.3.1.5 Counter-Controlled Loops in Functional Languages


Counter-controlled loops in imperative languages use a counter variable, but
such variables do not exist in pure functional languages. Rather than itera-
tion to control repetition, functional languages use recursion. Rather than
a statement, functional languages use a recursive function. Counting loops
can be simulated in functional languages as follows: The counter can be a
parameter for a function that repeatedly executes the loop body, which can
be specified in a second function sent to the loop function as a parameter. So,
such a loop function takes the body function and the number of repetitions
as parameters.
The general form of an F# function for simulating counting loops, named
forLoop in this case, is as follows:


let rec forLoop loopBody reps =
if reps <= 0 then
()

Free download pdf