either

Jonathan M Davis jmdavisProg at gmx.com
Sun Jan 9 15:49:59 PST 2011


On Sunday 09 January 2011 12:28:23 Andrei Alexandrescu wrote:
> On 1/9/11 2:09 PM, Tomek Sowiński wrote:
> > I really don't dig the whole helper structs with overloaded operators
> > thing. It complicates the implementation (more work for compiler to grok
> > and inline) and you're never really sure what it does unless you read
> > the docs (or the complicated implementation).
> > 
> > It should be as simple as this:
> > 
> > bool any(E, Ts...)(E e, Ts args) {
> > 
> >       foreach (a; args)
> >       
> >           if (a == e)
> >           
> >              return true;
> >       
> >       return false;
> > 
> > }
> > 
> > unittest
> > {
> > 
> >       assert(!"abac".any("aasd", "s"));
> >       assert("abac".any("aasd", "abac", "s"));
> >       // assert(1.any(1,2,3));    // doesn't compile for now, bug 3382
> > 
> > }
> > 
> >> Turns out this is very useful in a variety of algorithms.
> > 
> > Very!
> > 
> >> I just don't
> >> know where in std this helper belongs! Any ideas?
> > 
> > Maybe std.algorithm? It bears vague resemblance to max().
> 
> Aha, so this encodes the predicate in the operation. With a general
> predicate, that would be:
> 
> if (any!"a != b"(expr, 1, 2, 5)) { ... }
> 
> The advantage over
> 
> if (expr != 1 || expr != 2 || expr != 5)) { ... }
> 
> is terseness and the guarantee that expr is evaluated once (which is
> nice at least for my code).
> 
> This looks promising and well integrated with the rest of Phobos. Should
> I add it? And if I do, is "any" the name?

Well, I would expect any to be used for testing whether a predicate is true for 
any element in a given range (as discussed in 
http://d.puremagic.com/issues/show_bug.cgi?id=4405 ), which is similar to what 
canFind() already does (though I'd very much like generalized any() and all() 
functions as discussed in that enhancement request).

Here, you are trying to do something similar, but in essence, you're giving it 
the needle first and then variadic lists to make up the haystack. It makes me 
want to try and combine what you're trying to do with any()/canFind(), but given 
that that would entail flipping the predicate, I'm not sure that that would work 
very well.

Actually, I'd wonder if it would make sense to try and give an overload of 
std.algorithm.equal() which does what you're trying to do here. Either that or 
make it equalAny(), since it's using a predicate for equality in the same sense 
that equal() is.

Regardless, I'd quite like any() to be used for checking whether a predicate is 
true for any element in a given range (with all() being used to check whether 
the predicate is true for all of the elements of a range), and using any() for 
what you're suggesting goes against that, even though it's quite similar.

- Jonathan M Davis


More information about the Digitalmars-d mailing list