www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - How to check all values in a range are equal to some predicate?

reply Andrej Mitrovic <andrej.mitrovich gmail.com> writes:
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?
Sep 24 2011
parent travert phare.normalesup.org (Christophe) writes:
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
Sep 26 2011