Note: This website is archived. For up-to-date information about D projects and development, please visit wiki.dlang.org.

Factorial (by Recursive Template) Example

Part of TemplatesCategory

Description

Demonstrates how a recursive template function can be instantiated implicitly.

Related Example

Factorial by non-recursive template: FactorialTemplateExample

Example

import std.stdio : writefln;


template factorial(int n : 0)
{
    enum { factorial = 1 }
}

template factorial(int n : 1)
{
    enum { factorial = 1 }
}

template factorial(int n)
{
    enum { factorial = n* factorial!(n-1) }
}


void main()
{
    writefln("0! = ", factorial!(0));
    writefln("1! = ", factorial!(1));
    writefln("2! = ", factorial!(2));
    writefln("3! = ", factorial!(3));
    writefln("4! = ", factorial!(4));
    writefln("5! = ", factorial!(5));
    writefln("6! = ", factorial!(6));
    writefln("7! = ", factorial!(7));
}

Batch File

@echo off
set pgm=FactorialRecursiveTemplateExample
dmd %pgm%.d
%pgm%.exe
pause
erase %pgm%.obj
erase %pgm%.map

Output

0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040

Tested Compiler/Platform

Tested with Digital Mars D Compiler v0.176 on Windows 2000.

Souce

Based on code from the D Specification.