Names with trailing question mark

Jacob Carlborg doob at me.com
Tue Oct 4 07:22:27 PDT 2011


On 2011-10-04 15:03, Timon Gehr wrote:
> On 04.10.2011 01:37, bearophile wrote:
>> Predicates are quite common. In D I presume the standard way to write
>> them is with a name like "isFoo". In other languages they are written
>> in other ways:
>>
>>
>> if (foo.isEven) {}
>> if (foo.isEven()) {}
>> filter!isEven(data)
>>
>> if (foo.evenQ) {}
>> if (foo.evenQ()) {}
>> filter!evenQ(data)
>>
>> if (foo.even?) {}
>> if (foo.even?()) {}
>> filter!even?(data)
>>
>> Other usages:
>>
>> contains?
>> areInside ==> inside?
>>
>>
>> I don't remember serious recent discussions here about that last form.
>> Allowing a single trailing question mark in D names has some advantages:
>>
>> 1) It gives a standard way to denote a predicate, so it becomes very
>> easy to tell apart a predicate from other non predicate things.
>>
>> 2) It allows for short names.
>>
>> 3) A single question mark is easy and quick to write on most keyboards.
>>
>> 4) It is used in other languages, as Ruby, and people seem to
>> appreciate it.
>>
>> 5) Its meaning is probably easy enough to understand and remember.
>>
>>
>>
>> Some disadvantages:
>> 1) "?" makes code less easy to read aloud.
>>
>> 2) It is less good to use the trailing "?" in functions that aren't
>> properties, the syntax becomes less nice looking:
>> if (foo.even()?)
>>
>> 3) The usage of the trailing "?" in names forbids later different
>> usages for it, like denoting nullable types.
>>
>> 4) In expressions that use the ternary operator and a property
>> predicate (without leading ()) it becomes a bit less easy to read
>> (example from http://stackoverflow.com):
>>
>> string customerName = user.loggedIn? ? user.name : "Who are you?";
>>
>> I think this too gets accepted:
>> string customerName = user.loggedIn??user.name:"Who are you?";
>>
>> I vaguely like the idea of using a trailing question mark in predicate
>> names.
>>
>> Bye,
>> bearophile
>
> This would break lexer/parser separation and make the parsing of
> conditional expressions painfully complicated and ambiguous.
>
> For example, how would you parse the following?
>
> foo?+foo?(a):b;
>
> it could be
>
> foo ? (+foo?(a)) : b;
>
> or
>
> ((foo?)+foo) ? (a) : b;

I would say it would be illegal and that the ternary operator requires a 
space before the question mark. It works like this in Ruby as well. It 
would be parsed like this:

(foo?) + (foo?(a)) : b

Have a look at: http://d-programming-language.org/lex.html

"The source text is split into tokens using the maximal munch technique, 
i.e., the lexical analyzer tries to make the longest token it can."

"For example >> is a right shift token, not two greater than tokens."

It's the same here. Since "?" would be a legal symbol in a method name, 
"foo?" is the method name, not "foo" and "?".

-- 
/Jacob Carlborg


More information about the Digitalmars-d mailing list