Names with trailing question mark

Timon Gehr timon.gehr at gmx.ch
Tue Oct 4 06:03:38 PDT 2011


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'd like to have trailing ' in identifiers though, having them would not 
introduce ambiguities or break existing code.

immutable x=1;
immutable x'=x+2;









More information about the Digitalmars-d mailing list