Adding the ?. operator to D
ddcovery
antoniocabreraperez at gmail.com
Fri Sep 18 22:33:56 UTC 2020
On Saturday, 12 September 2020 at 19:26:30 UTC, Stefan Koch wrote:
> On Saturday, 12 September 2020 at 16:51:20 UTC, Per Nordlöw
> wrote:
>> Has there been any discussions on adding the ?. operator to
>> simplify structure matching on class trees typically found in
>> compilers such as dmd.
>
> Hmm the problem with .? making implicit null checks is that it
> encourages
> null checks.
> Rather than encouraging a state in which existence and logic
> are statically asserted.
Absolutely.
Using a "functional" orientation with "only(p)" as alternative to
"MayBe" monad, an unwrapping with "fold( fun )(initialValue)"
function with a default value:
> void main(){
> Person p = new Person("Peter", new Person("John",null));
> auto name = only(p).
> filter!"a !is null".map!"a.father".
> filter!"a !is null".map!"a.father".
> filter!"a !is null".map!"a.name".
> fold!"b"("Unknown");
> writeln( format!"The name of your great grandfather is
> %s"(name) );
> }
>
> class Person {
> string name;
> Person father;
> this(string name, Person father) {
> this.name=name;
> this.father=father;
> }
> }
We can unify
> .filter!"a !is null".map!(func)
as an alternative template
> .n!(func)
and unfold using
> .getOrElse(defaultValue)
that unifies
> .fold!"b"(initValue)
The result could be
> auto name =
> only(p).n!"a.father".n!"a.father".n!"a.name".getOrElse("Unknown");
That is verbose, may be inneficient, but a nice experiment :-)
More information about the Digitalmars-d
mailing list