On 2010-11-15 14:27, spir wrote:
On Mon, 15 Nov 2010 13:15:50 +0100
Per Ångström<[email protected]>  wrote:
string func(string s)
{
      /++
      // A handy feature of many scripting languages, but not in D
      // (in D, the type of the or-expression is bool):
      // The type of the or-expression is the type of the first
      // sub-expression that evaluates to true.
      return s || "default";
      +/
      // The D equivalent, arguably more readable but also more verbose:
      return s ? s : "default";
}

More verbose?
        Real programmers *want* to type 3 more characters when this makes code 
clearer!
;-)

Verbosity is not only about more code to type, it's also about more code to read. My example was brief so of course that difference is negligible. Here's a somewhat more complex example which forces a trade-off between an extra temporary variable, evaluating the same expression twice or using a template:

/++
Simulates type-returning or-expression
+/
template or(T) {
    T _(T a, lazy T b) {T tmp = a; return tmp ? tmp : b;}
}

void m() {
    /+ least verbose, invalid D:
    string s = func("...") || "default";
    +/

    /+ valid D, but requires extra temp variable:
    string tmp = func("...");
    string s = tmp ? tmp : "default";
    +/

/+ valid D, no temp variable but two (hopefully idempotent) function calls:
    string s = func("...") ? func(".,.") : "default";
    +/

    // valid D, but arguably ugly:
    string s = or!string._(func("..."), "default");
}
--
Per Å.

Reply via email to