www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Pattern matching templates?

I think the template definition in D is quite nice for an 
imperative language. However, I think it would be even better if 
it was more geared towards pattern matching, even of the simple 
kind that you find in languages like XSLT. ( Forgive me if D 
already supports this. )

Assumptions about desirable properties for a standard library:
1. it should be bug free
2. it should be highly portable
3. it should only cover generally useful functionality
4. it should support composing (follows from 1 and3)

A cleaned up version of Phobos would cover this quite well. 
However there are other desirable properties that is nice to have 
for system level language:

1. you should be able to optimize any bottle necks with ease
2. optimization should not make the program less readable
3. optimization should not make the program less portable
4. sharing of optimizations should be encouraged
5. you should be able to turn optimizations on/off for unit 
testing
6. the programmer should be able to add constraints/hints to aid 
optimization

Pattern matching can help here. For simplicity, lets assume a 
pattern operator "#" that converts memberfunctions like 
"this.func(param)" into "#func(this,param)" and that you can 
assign to a type-variable "functype" so that you get  
"functype#func(this,param)".

E.g. f you set a string to uppercase with something like 
(pseudocode):

somestring.map(touppercase)

You should be able pattern match this as:

patternmatch a#map(this1,b#touppercase) with priority(0.5) if 
extra_constraints_on(a,b){
     // asm-code here
}

or

patternmatch a#map(this1,b#touppercase) with 
priority(calc_priority_for_constraints(a,b)){
     // asm-code here
}

or for more general matching

patternmatch a#(this1,b#) with 
priority(calc_priority_for_constraints(a,b)){
     // asm-code here
}

The advantage of this is:
- you separate optimizations from the basic semantics
- you can unit test by comparing optimizations to the reference 
implementation
- you can easily swap out different optimizations

And:

It affords sharing of optimizations with others. Bugs are not so 
serious, because you always can revert to the reference 
implementation that is bug free.

Contributing to phobos requires a certain amount of experience 
with D and a lot of testing for bugs.

Contributing to optional optimizations to compositions of 
functionality only requires you to look at your own programs and 
then submit your patternmatching code.

That lowers the threshold for improving the efficiency of phobos 
without sacrificing generality or bug-free-ness of the library.

Speed issues can be resolved by doing pattern matching on 
multiple levels and JIT the last stage.

Conflicting matching can be resolved by giving a float based 
priority that can be set in the definition, on imports and on use.

Maybe nothing for D2, but perhaps for D3?

Ola.
Jan 28 2014