(1) basic usage
|
def main():
# v1
for i in range(5):
print(i)
# v2
for i in range(0, 5):
print(i)
|
import std.stdio;
void main()
{
foreach (i; 0 .. 5)
{
writeln(i);
}
}
|
|
- 0 is included
- 5 is NOT included (excluded)
|
Output:
In D, ..
is the range operator. However, it doesn't return a range. iota()
, for instance, returns a range.
Generate the index AND the value
(2) index AND value
|
def main():
words = ["aa", "bb", "cc"]
# 1
for w in words:
print(w)
"""
aa
bb
cc
"""
# 2
for idx, w in enumerate(words):
print(idx, ":", w)
"""
0 : aa
1 : bb
2 : cc
"""
|
import std.stdio;
void main()
{
string[] words = ["aa", "bb", "cc"];
// 1
foreach (w; words)
{
writeln(w);
}
/*
aa
bb
cc
*/
// 2
foreach (idx, w; words)
{
writeln(idx, ": ", w);
}
/*
0: aa
1: bb
2: cc
*/
}
|
Print a string char by char
(3) print a string char by char
|
def main():
s = "görög"
for c in s:
print(c)
"""
g
ö
r
ö
g
"""
|
import std.stdio;
void main()
{
string s = "görög";
// problem
foreach (char c; s)
{
writeln(c);
}
/*
g
�
�
r
�
�
g
*/
// solution (notice the dchar type)
foreach (dchar c; s)
{
writeln(c);
}
/*
g
ö
r
ö
g
*/
}
|
In D, a string
uses UTF-8 encoding. When iterating through a string with a char
, we iterate over the bytes. However, a dchar
is 4 bytes and it can store any Unicode character.
Modify the elements during the loop
(4) update the elements
|
def main():
numbers = [1, 2, 3]
# problem: n is a copy of the current element
for n in numbers:
n *= 2
#
print(numbers) # [1, 2, 3]
# solution
for i in range(len(numbers)):
numbers[i] *= 2
#
print(numbers) # [2, 4, 6]
|
import std.stdio;
void main()
{
int[] numbers = [1, 2, 3];
// problem: n is a copy of the current element
foreach (n; numbers)
{
n *= 2;
}
writeln(numbers); // [1, 2, 3]
// solution: use ref
foreach (ref n; numbers)
{
n *= 2;
}
writeln(numbers); // [2, 4, 6]
}
|
The ref
keyword makes n
an alias of the current element. Thus, modifying n
will modify the current element.
foreach_reverse
foreach_reverse
allows us to iterate backwards. However, you can have the same effect by using retro()
, which returns a reverse range.
(1) title
|
def main():
words = ["aa", "bb", "cc"]
for w in reversed(words):
print(w)
|
import std.stdio;
import std.range; // retro()
void main()
{
string[] words = ["aa", "bb", "cc"];
// v1
foreach_reverse (w; words)
{
writeln(w);
}
// v2
foreach (w; words.retro)
{
writeln(w);
}
}
|
Output in all cases: