www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - pattern matching

reply %u <asmasm hotmail.com> writes:
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
Sep 06 2011
next sibling parent bearophile <bearophileHUGS lycos.com> writes:
%u:

 is that work?
In D unfortunately there is no pattern matching on the run-time values of function arguments. But I don't really understand what you are asking me, sorry. Bye, bearophile
Sep 06 2011
prev sibling parent Jonathan M Davis <jmdavisProg gmx.com> writes:
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
Sep 06 2011