RosettaCodeData/Task/Symmetric-difference/D/symmetric-difference.d

28 lines
745 B
D
Raw Permalink Normal View History

2013-04-11 01:07:29 -07:00
import std.stdio, std.algorithm, std.array;
struct Set(T) {
immutable T[] items;
2013-10-27 22:24:23 +00:00
Set opSub(in Set other) const pure nothrow {
return items.filter!(x => !other.items.canFind(x)).array.Set;
2013-04-11 01:07:29 -07:00
}
2013-10-27 22:24:23 +00:00
Set opAdd(in Set other) const pure nothrow {
2013-04-11 01:07:29 -07:00
return Set(this.items ~ (other - this).items);
}
}
2013-10-27 22:24:23 +00:00
Set!T symmetricDifference(T)(in Set!T left, in Set!T right)
pure nothrow {
2013-04-11 01:07:29 -07:00
return (left - right) + (right - left);
}
void main() {
2013-10-27 22:24:23 +00:00
immutable A = ["John", "Bob", "Mary", "Serena"].Set!string;
immutable B = ["Jim", "Mary", "John", "Bob"].Set!string;
2013-04-11 01:07:29 -07:00
writeln(" A\\B: ", (A - B).items);
writeln(" B\\A: ", (B - A).items);
writeln("A symdiff B: ", symmetricDifference(A, B).items);
}