Pattern matching is-expressions

Stefan Koch uplink.coder at
Wed Aug 19 07:29:18 UTC 2020

Hi there,

Recently I have been thinking about converting commonly used is 
expressions into __traits,
since having that makes type functions more consitent.

So let me first talk about the problem.

let's say for type T you wanted write an is expression which 
matchs a on slice types.
you would write:
static if (is(T == U[], U))
     pragma(msg, "I have seen a slice of type " ~ U.stringof);
Which means If there is any U such that U[] is the same type as 
T, return true and inject the name U into the scope below.
As long as that scope is a `static if`.

We are effectively changing the ast here.
The is expression is not just a query but also injecting a node.

Note: what I wrote above is what's in the spec.
In reality the is expression makes U a name immediately and not 
just in the static if scope below.

consider this example:

`static if (is(P[0] S == super) && is(S[0] == ASTNode))`
Which means:
iff there is a tuple P AND P has at least one element AND for 
tuple P the first element of P is a class or interface AND P[0] 
is not object or the first interface in an interface hierachy, 
introduce a new name S which is a tuple of the parent classs or 
interfaces of P[0], THEN evluate the is expression to true;
AND iff there is a tuple S AND S has at least one element AND 
there is a type called ASTNode AND the first elemennt of S is the 
type called ASTNode THEN evaluate the is-expression to true.
If the latter is expression is true that implies that the former 
is expression was true.

We can see that S is a valid tuple immediately after, (and even 
inside), the expression which created it.
That's helpful in this case because otherwise if'd have to one 
nest more `static if`.

To make the issue clearer let me reframe this a little.
this expression is(P S == super) is rougly equivalent to the 
"Do you have a father?"

So you ask that question and the answer is "Yes I do have a 
father, his name is Bernd, also that's him just there, and he is 
going to live with you now."

That is a problem if you don't have room for Bernd at your home.

If you write the following into a new file
int[] ia;
pragma(msg, "ia is an array ", is(typeof(ia) == U[], U), " and 
it's element type is: ", U);

The output will be:
`ia is an array true and it's element type is: int`

which you can check here

This works because the is expression installed the name U in your 

At least in my opinion this is very diffrent to the way D behaves 
anywhere else in the language.

What do you think?


More information about the Digitalmars-d mailing list