Lazy range of hashes?
Ali Çehreli
acehreli at yahoo.com
Sun Aug 26 00:29:12 PDT 2012
On 08/25/2012 05:30 PM, Andrej Mitrovic wrote:
> On 8/26/12, bearophile<bearophileHUGS at lycos.com> wrote:
>> This seems to work:
>
> It seems it's as simple as defining a struct:
>
> struct LazyHash(T...)
> {
> T hashes;
>
> bool opIn_r(X)(X x)
> {
> foreach (hash; hashes)
> {
> if (x in hash)
> return true;
> }
>
> return false;
> }
> }
>
> auto lazyHash(T...)(T t)
> {
> return LazyHash!T(t);
> }
>
> void main()
> {
> auto x = ["foo" : 1];
> auto y = ["bar" : 2];
>
> assert("bar" in lazyHash(x, y));
> assert("barx" !in lazyHash(x, y));
> }
>
> I didn't even have to define a ctor since field assignment works.
Cool! :) If the operator returns the pointer to the element, then the
callers can access its value as well:
auto opIn_r(X)(X x)
{
foreach (hash; hashes)
{
auto p = x in hash;
if (p)
return p; // <-- return the pointer
}
return null;
}
// ...
import std.stdio;
auto p = "foo" in lazyHash(x, y);
if (p) {
writeln(*p); // <-- the user can access the value
}
Ali
More information about the Digitalmars-d-learn
mailing list