September 2022 For loops
For
loops exist in almost all programming languages (except functional ones) as it serves incredibly useful and convinient practicality for certain problems encountered in day-to-day programming.
Strict works with various forms of for
loops and they are very simple to write. The expression
in the for
loop basically is an iterator which iterates through the series of values.
Let's look at a very simple example of the for
loop:
for number in numbers
log.Write(number)
Above is given a very simple example that is pretty straightforward : it iterates through the list of numbers and logs each of the number. numbers
is an iterable and number
is an explicit iterator variable.
How implicit variables work
We can rewrite previous example in a more convinient, "Strict"
way. for
loops in Strict has two variables by default - index
& value
. The aformentioned variables are implicit, meaning they don't need to be declared as they always exist within the scope of the loop.
Let's rewrite the previous example using the implicit value
variable:
for numbers
log.Write(value)
This code does exactly the same thing as above. Note that value
is basically a pointer to the instance of the current class (like this
in C/C++/C#), but as soon as the scope of the loop is entered, it becomes the iterator variable.
index
works similarly, but obviously it holds the index of the element.
for ("Hello", "World", "!")
log.Write(index)
This would log 0, 1 and 2.
Let's check out this function, which is a part of Range.strict and just sums the value from start of the range to the endo of the range:
Sum
Range(2, 4).Sum is 2 + 3 + 4
Range(42, 45).Sum is 42 + 43 + 44
let result = Mutable(0)
for item in Range(value.Start, value.End)
result = result + item
result
We declare a mutable variable, which is supposed to hold the result of the summation, then we iterate through the Range, perform the sum of the item and return the result. Now this can be rewritten in a much easier way by utilizing the features of Strict.
Sum
Range(2, 4).Sum is 2 + 3 + 4
Range(42, 45).Sum is 42 + 43 + 44
for value
+ value
This does exactly the same as above, the return
statement AND the summation is simply inlined in the for scope producing the result.
Nested loops
In Strict, you can take full adventage of nested loops, and they're pretty straightforward.
let weeks = 3
let days = 7
for weeks
log.Write("Week: " + index + 1);
for days
log.Write("Day: " + index + 1)