Saturday, June 18, 2011

A much simpler question: Shortcut 'and' and 'or'

I was recently reading some blog posts comparing various languages, and in particular a "wish list" of language features that was informative. One of the things that the author wished for is to have the 'and' and 'or' operators work like they do in Python / Perl / JavaScript and other dynamic languages - specifically, that they could take non-boolean arguments, and return a non-boolean value.

So for example, a common JavaScript idiom is this:

function makeButton(opt_title) {
  this.title = opt_title || "OK";
}

The 'title' property of the object will be assigned the value of 'opt_title' if it evaluates to true, otherwise the default string "OK" will be used.

My question for the readers is - does this make sense in a statically typed language? There are a number of issues to consider:

Both arguments to the logical operator would have to have the same static type (or at least, be convertible to a common type). The resulting value would also have the same static type. From a compiler standpoint, this is fairly easy, no different really than the arithmetic operators which also require that both sides be promotable to the same type. The real question is whether this restriction - that the two sides as well as the result value have the same static type - makes the feature less useful than it would in a dynamic language.

The other issue is that both arguments would need to be implicitly convertible to boolean types. C and C++ implicitly map the integer value 0 and the pointer value NULL to boolean false. Other languages go farther and map the empty string "" and the empty array [] to false as well. And of course, in Tart you also have unions which can have 'void' as a member, so I'm assuming that those would be convertible to false as well. And what about floats? Or decimal numbers? To be completely general, we'd have to allow user-defined types to declare their own implicit conversions to boolean.

I've avoided such implicit conversions up to this point because in my experience they are a source of potential confusion. Right now, you have to explicitly compare values with 0 or NULL or the empty string in order to convert the value into a boolean.

Allowing implicit conversion to booleans would have far-reaching changes. For one thing, the 'if', 'for' and 'while' statements would have to change to be consistent with the 'and' and 'or' operators. It would be confusing otherwise - given a set of strings s1 and s2, if I'm allowed to say 's1 or s2' I would also expect to be able to say 'if s1' or 'while s1'.

Do you think that the convenience worth the possible confusion?

No comments:

Post a Comment