either

Nick Sabalausky a at a.a
Sun Jan 9 12:15:22 PST 2011


"Andrei Alexandrescu" <SeeWebsiteForEmail at erdani.org> wrote in message 
news:igcvll$29k5$1 at digitalmars.com...
>I wrote a simple helper, in spirit with some recent discussions:
>
> // either
> struct Either(Ts...)
> {
>     Tuple!Ts data_;
>     bool opEquals(E)(E e)
>     {
>         foreach (i, T; Ts)
>         {
>             if (data_[i] == e) return true;
>         }
>         return false;
>     }
> }
>
> auto either(Ts...)(Ts args)
> {
>     return Either!Ts(tuple(args));
> }
>
> unittest
> {
>     assert(1 == either(1, 2, 3));
>     assert(4 != either(1, 2, 3));
>     assert("abac" != either("aasd", "s"));
>     assert("abac" == either("aasd", "abac", "s"));
> }
>
> Turns out this is very useful in a variety of algorithms. I just don't 
> know where in std this helper belongs! Any ideas?
>

For years I've just been doing this:

if( [1, 2, 3].contains(1) )

Although I think I needed to write a new "contains" to wrap existing 
functions when I switched from Tango to Phobos.

Of course, "1 in [1,2,3]" would be much better ;) But whateever. Either way.

But I suppose your "either" avoids an allocation, doesn't it? (And I'd lean 
more towards "any" than "either" like the other people).





More information about the Digitalmars-d mailing list