How to check all values in a range are equal to some predicate?

Christophe travert at phare.normalesup.org
Mon Sep 26 05:07:29 PDT 2011


Andrej Mitrovic , dans le message (digitalmars.D.learn:29755), a écrit :
> I want to use this in my unittests:
> 
> assert(allEqual(Foo(1), obj1, obj2, obj3));
> 
> How would you implement a function like allEqual(needle, objects...) ?
> Maybe via reduce?


I would use find. (the code was not compiled/tested at all)

bool allEqual(R)(R r) if (isInputRange!R)
{
    auto a = r.front;
    r.popFront();
    return find!(b){return a!=b;}(r).empty;
}


and direct '==' operator for tuples:

bool allEqual(T...)(T t)
{
    return t[0] == t[1] && allEqual(t[0], t[2..$]);
}

with an appropriate filter if I want to make something nice.


-- 
Christophe


More information about the Digitalmars-d-learn mailing list