either

Tomek Sowiński just at ask.me
Sun Jan 9 16:34:13 PST 2011


Andrei Alexandrescu napisał:

> > bool any(alias pred = "a==b", E, Ts...)(E e, Ts args) if(Ts.length>  1 || !isTuple!Ts) {
> >       foreach (a; args)
> >           if (binaryFun!pred(a, e))
> >              return true;
> >       return false;
> > }
> >
> > unittest
> > {
> >       assert(!"abac".any("s"));
> >       assert(!"abac".any("aasd", "s"));
> >       assert("abac".any("aasd", "abac", "s"));
> > }
> >
> > /// Unpacks a single tuple.
> > bool any(alias pred = "a==b", E, T)(E e, T t) if(isTuple!T) {
> >      return any!(pred, E, T.Types)(e, t.field);
> > }
> >
> > unittest
> > {
> >       assert(any("abac", tuple("aasd", "abac", "s")));
> >       assert(find!any([5,3,7,9,4,5,7], tuple(2,4,6)) == [4,5,7]);    // cool!
> > }  
> 
> Hm, I don't see why not asking the owner of the tuple to type .expand.

I'd ask the reverse question -- why "abc".any(tuple("cba", "abc")) shouldn't mean "abc".any("cba", "abc") ? It's natural.

The only difficulty I see is behaving well for the degenerate case ("abc".any("abc") works, so tuple(1,2).any(tuple(1,2)) should work too). That, I believe, can be solved by additional template constraints on the unpacking overload.

Another good reason -- this doesn't compile:

assert(find!any([5,3,7,9,4,5,7], tuple(2,4,6).expand) == [4,5,7]);

test.d(24): Error: template std.algorithm.find(alias pred = "a == b",R,E) if (isInputRange!(R) && is(typeof(binaryFun!(pred)(haystack.front,needle)) : bool)) does not match any function template declaration
test.d(24): Error: template std.algorithm.find(alias pred = "a == b",R,E) if (isInputRange!(R) && is(typeof(binaryFun!(pred)(haystack.front,needle)) : bool)) cannot deduce template function from argument types !(any)(int[],int,int,int)
test.d(24): Error: template instance errors instantiating template

-- 
Tomek



More information about the Digitalmars-d mailing list