Where should I put a `condp` like function?

H. S. Teoh hsteoh at quickfur.ath.cx
Sun Apr 14 22:00:18 PDT 2013


On Sun, Apr 14, 2013 at 11:46:04PM -0400, Nick Sabalausky wrote:
> On Mon, 15 Apr 2013 02:48:27 +0200
> "bearophile" <bearophileHUGS at lycos.com> wrote:
> 
> > Idan Arye:
> > 
> > > You can't do those things with `switch` because it's a 
> > > statement.
> > 
> > In various Reddit threads I see people almost angry against the
> > statement-expression distinction in contemporary programming
> > languages. I am just starting to understand them.
[...]

I think C was one of the early innovators in treating all function calls
as expressions (or equivalently, allowing function calls to be
statements). Many languages of that era differentiated between functions
and procedures (== void functions), and treat calls to the latter
strictly as statements.


> I've never seen a big problem with the statement vs expression
> distinction, and I think the "statements == expresions" languages
> sometimes takes things slightly overboard in the process of forcing
> them into the same mold. However, I've *definitely* wished on many
> occasions that D's switch could be used as an expression like in Haxe.

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;
		};
	}

This can help readability a lot when the outer expression is
complicated.

It's reminiscient of Dijkstra's guarded command language, which has a
condition statement that contains a bunch of predicate-statement pairs;
during execution, one statement is chosen from the conditional block
whose predicate evaluates to true. At least one predicate must be true
at any time, otherwise it is an error (similar to D's final switches).
If more than one predicate evaluates to true, the choice is
non-deterministic. The implementation can choose to provide a built-in
uniform randomizer for this case.

This lets you state the preconditions of statements up-front, thereby
reducing mistakes caused by implicit assumptions that fail to hold. With
code that is continually being revised, this can help prevent a lot of
bugs.


T

-- 
Fact is stranger than fiction.


More information about the Digitalmars-d mailing list