Where should I put a `condp` like function?

Idan Arye GenericNPC at gmail.com
Thu Apr 18 06:58:45 PDT 2013


On Wednesday, 17 April 2013 at 13:09:45 UTC, Nick Treleaven wrote:
> On 15/04/2013 06:00, H. S. Teoh wrote:
>> Allowing arbitrary predicates and switch-as-expression allows 
>> you to
>> write code that shows intent very clearly:
>>
>> 	// In pseudo-D syntax
>> 	void fill(T)(T image, int x, int y) {
>> 		image[x,y] = switch {
>> 			case isFillable(image,x,y): fillColor;
>> 			case isBorder(image,x,y): borderColor;
>> 			default: defaultColor;
>> 		};
>> 	}
>
> We could use a conditional operator chain:
>
> image[x,y] = isFillable(image,x,y) ? fillColor :
>              isBorder(image,x,y) ? borderColor :
>              defaultColor;

Naturally - even as statements, a `switch` statement without a 
switch expression is no better than a chain of `if`-`else`s.

Now, consider this hackish use of `predSwitch`: 
https://gist.github.com/someboddy/5412843
This is actual D code(you need 
https://github.com/D-Programming-Language/phobos/pull/1259 to run 
it), and it prints:

*****
*...*
*.+.*
*...*
*****

As expected. This does have an advantage over a chain of 
`if`-`else`s or ternary operators - you only need to write the 
argument list once.


More information about the Digitalmars-d mailing list