Skip to content

Commit 06b69f9

Browse files
authored
[spec] Improve foreach on a tuple range docs (#3832)
State that one variable will be a value sequence. Use finite range.
1 parent 0f42807 commit 06b69f9

File tree

1 file changed

+14
-13
lines changed

1 file changed

+14
-13
lines changed

spec/statement.dd

Lines changed: 14 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -973,41 +973,42 @@ $(H4 $(LNAME2 front-seq, Multiple Element Values))
973973
expands to a $(DDSUBLINK spec/template, homogeneous_sequences, value sequence)
974974
whose length matches the number of variables. Each variable is assigned
975975
to the corresponding value in the sequence.
976+
If there is only one variable, it will be a value sequence.
976977
)
977978

978979
$(SPEC_RUNNABLE_EXAMPLE_RUN
979980
---
981+
import std.stdio;
982+
983+
// simple version of std.typecons.Tuple
980984
struct Tuple(Types...) // takes a TypeSeq
981985
{
982986
Types items; // ValueSeq
983987
alias items this; // decay to a value sequence
984988
}
985989

986-
// Infinite range with a repeating element, which is a tuple
990+
string s = "hello";
991+
987992
struct TupleRange
988993
{
989-
enum front = Tuple!(char, bool, int)('a', true, 2);
990-
enum bool empty = false;
991-
992-
void popFront() {}
994+
size_t i;
995+
auto front() => Tuple!(size_t, char)(i, s[i]);
996+
bool empty() => i >= s.length;
997+
void popFront() { i++; }
993998
}
994999

9951000
void main()
9961001
{
9971002
// Tuple destructuring
998-
foreach (a, b, c; TupleRange())
1003+
foreach (i, c; TupleRange())
9991004
{
1000-
assert(a == 'a');
1001-
assert(b == true);
1002-
assert(c == 2);
1003-
break;
1005+
writeln(i, ": ", c);
10041006
}
1007+
writeln();
10051008
// Tuple variable
10061009
foreach (tup; TupleRange())
10071010
{
1008-
assert(tup[0] == 'a');
1009-
assert(tup == TupleRange.front);
1010-
break;
1011+
writefln("(%s, %s)", tup[0], tup[1]);
10111012
}
10121013
}
10131014
---

0 commit comments

Comments
 (0)