Takes pairs of predicates and transforms and uses the first transform that a predicate return true for.
1 alias lessThanZero = (a) => a < 0; 2 alias greaterOrEqualThan10 = (a) => a >= 10; 3 alias identity = (a) => a; 4 alias negate = (a) => -a; 5 6 alias abs = cond!( 7 a => a == 1, 42, 8 2, a => a * 2, 9 3, 999, 10 lessThanZero, negate, 11 greaterOrEqualThan10, identity, 12 a => a * 100, 13 ); 14 15 assert(abs(1) == 42); 16 assert(abs(2) == 4); 17 assert(abs(3) == 999); 18 assert(abs(4) == 400); 19 assert(abs(5) == 500); 20 assert(abs(-3) == 3); 21 assert(abs(11) == 11); 22 23 alias str = cond!( 24 a => a < 1, "1", 25 a => a < 5, "5", 26 a => a < 10, "10", 27 "moar" 28 ); 29 30 assert(str(0) == "1"); 31 assert(str(2) == "5"); 32 assert(str(7) == "10"); 33 assert(str(11) == "moar");
Create a function that encapsulates if/else-if/else logic