pattern matching

Jonathan M Davis jmdavisProg at gmx.com
Tue Sep 6 14:47:05 PDT 2011


On Tuesday, September 06, 2011 21:05:54 %u wrote:
> template factorial(int n) { const factorial = n * factorial!(n-1); }
> template factorial(int n : 1) { const factorial = 1; }
> 
> i think this pattern matching or like it, can i do the same thing with
> regular function
> 
> int factorial(int n) {
>  return n* factorial(n-1);
> return 1 ;
>  }
> 
> int factorial(int n : 0) {
> return 1 ;
>  }
> 
> is that work?
> 
> thanks in advance

No. It works with templates, because it's generating code. Unless you're 
dealing with class member functions, all function calls are determined at 
compile time, so they can't depend on the values of their arguments at all. 
With class member functions, they use the class' vtable to do polymorphic 
calls and call the function in the type which is the actual type of that 
object (as opposed to what the referenc is). e.g.

class A
{
    void func(int i) {writeln("A");}
}

class B : A
{
    void func(int i) {writeln("B";}
}

void main()
{
    A a = new B;
    a.func();
}

will print "B". And that's not pattern matching. It's just simple 
polymorphism. The closest that you could get to pattern matching with function 
calls is with if statements.


if(n == 0)
    return factorial0();
else
    return factorialn(n);

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list