Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions changelog/std-array-bypair.dd
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
`std.array.byPair` now returns a `NamedTuple`

$(REF byPair, std, array) now returns a named tuple.

---
import std.array : byPair;
import std.typecons : Tuple;

int[string] dict = ["b": 2, "c": 3];
auto pairs = dict.byPair;
static assert(is(typeof(pairs.front) : Tuple!(string,int)));

// access by index (existing way)
assert(pairs.front[0] == "b");
assert(pairs.front[1] == 2);

// access by name (enabled with this release)
assert(pairs.front.key == "b");
assert(pairs.front.value == 2);
---
21 changes: 15 additions & 6 deletions std/array.d
Original file line number Diff line number Diff line change
Expand Up @@ -455,14 +455,17 @@ Construct a range iterating over an associative array by key/value tuples.
Params: aa = The associative array to iterate over.

Returns: A $(REF_ALTTEXT forward range, isForwardRange, std,_range,primitives)
of Tuple's of key and value pairs from the given associative array.
of Tuple's of key and value pairs from the given associative array. The members
of each pair can be accessed by name (`.key` and `.value`). or by integer
index (0 and 1 respectively).
*/
auto byPair(AA : Value[Key], Value, Key)(AA aa)
{
import std.algorithm.iteration : map;
import std.typecons : tuple;

return aa.byKeyValue.map!(pair => tuple(pair.key, pair.value));
return aa.byKeyValue
.map!(pair => tuple!("key", "value")(pair.key, pair.value));
}

///
Expand All @@ -477,27 +480,33 @@ auto byPair(AA : Value[Key], Value, Key)(AA aa)
// Iteration over key/value pairs.
foreach (pair; aa.byPair)
{
pairs ~= pair;
if (pair.key == "b")
pairs ~= tuple("B", pair.value);
else
pairs ~= pair;
}

// Iteration order is implementation-dependent, so we should sort it to get
// a fixed order.
sort(pairs);
pairs.sort();
assert(pairs == [
tuple("B", 2),
tuple("a", 1),
tuple("b", 2),
tuple("c", 3)
]);
}

@system unittest
{
import std.typecons : tuple, Tuple;
import std.meta : AliasSeq;

auto aa = ["a":2];
auto pairs = aa.byPair();

static assert(is(typeof(pairs.front) == Tuple!(string,int)));
alias PT = typeof(pairs.front);
static assert(is(PT : Tuple!(string,int)));
static assert(PT.fieldNames == AliasSeq!("key", "value"));
static assert(isForwardRange!(typeof(pairs)));

assert(!pairs.empty);
Expand Down