On Thu, 28 Apr 2011 03:10:15 +0400, Andrej Mitrovic
<andrej.mitrov...@gmail.com> wrote:
I often see code written like this:
if (value == somevalue ||
value == someothervalue ||
value == yetanothervalue);
You could use the switch statement. But that introduces indentation,
and is rarely used for a couple of values.
I really like the "in" keyword, and I also like hashes since they can
potentially speed up look-ups compared to conventional arrays. So I
thought it would be cool to have a Hash template that constructs an
associative array which you can use especially in if statements when
you just want to know if a runtime value matches some predetermined
value.
Here's my attempt at writing it:
http://codepad.org/c4sYDSyR
Whaddya think?
Try this:
import std.stdio;
struct Set(Keys...)
{
bool opIn_r(Key)(Key key)
{
// TODO: Sort!(Keys)?
foreach (k; Keys) {
if (k == key) {
return true;
}
}
return false;
}
}
Set!(Keys) set(Keys...)() {
return Set!(Keys)();
}
void main()
{
int needle = 42;
bool result = needle in set!(1, 2, 3, 4, 5); // as opposed to needle == 1
|| needle == 2 || ...
writeln(result); // prints false
However, this only works with compile-time constants. Here is an extension
to that (albeit probably less efficient):
int k = 42;
result = 1 in dynset(1, k, 3, 4, 5);
writeln(result); // prints true
}
struct DynSet(Keys...)
{
this(Keys keys)
{
this.keys = keys;
}
bool opIn_r(Key)(Key key)
{
foreach (k; keys) {
if (k == key) {
return true;
}
}
return false;
}
private Keys keys;
}
DynSet!(Keys) dynset(Keys...)(Keys keys) {
return DynSet!(Keys)(keys);
}