Skip to content

Commit

Permalink
Merge pull request #930 from epi/master
Browse files Browse the repository at this point in the history
Added assocArray()
  • Loading branch information
Alex Rønne Petersen committed Dec 9, 2012
2 parents 467db2b + 383f77c commit c850e68
Showing 1 changed file with 44 additions and 0 deletions.
44 changes: 44 additions & 0 deletions std/array.d
Expand Up @@ -169,6 +169,50 @@ unittest
}
}

/**
Returns a newly allocated associative array out of elements of the input range,
which must be a range of tuples (Key, Value).
Example:
$(D_RUN_CODE
$(ARGS
----
auto a = assocArray(zip([0, 1, 2], ["a", "b", "c"]));
assert(a == [0:"a", 1:"b", 2:"c"]);
auto b = assocArray([ tuple("foo", "bar"), tuple("baz", "quux") ]);
assert(b == ["foo":"bar", "baz":"quux"]);
----
), $(ARGS), $(ARGS), $(ARGS import std.array;))
*/

auto assocArray(Range)(Range r)
if (isInputRange!Range && isTuple!(ElementType!Range)
&& ElementType!Range.length == 2)
{
alias ElementType!Range.Types[0] KeyType;
alias ElementType!Range.Types[1] ValueType;
ValueType[KeyType] aa;
foreach (t; r)
aa[t[0]] = t[1];
return aa;
}

unittest
{
static assert(!__traits(compiles, [ tuple("foo", "bar", "baz") ].assocArray()));
static assert(!__traits(compiles, [ tuple("foo") ].assocArray()));
static assert(__traits(compiles, [ tuple("foo", "bar") ].assocArray()));

auto aa1 = [ tuple("foo", "bar"), tuple("baz", "quux") ].assocArray();
assert(is(typeof(aa1) == string[string]));
assert(aa1 == ["foo":"bar", "baz":"quux"]);

auto aa2 = zip([0, 1, 2], ["a", "b", "c"]).assocArray();
assert(is(typeof(aa2) == string[int]));
assert(aa2 == [0:"a", 1:"b", 2:"c"]);
}

private template blockAttribute(T)
{
static if (hasIndirections!(T) || is(T == void))
Expand Down

0 comments on commit c850e68

Please sign in to comment.