This commit is contained in:
Ingy döt Net 2013-10-27 22:24:23 +00:00
parent 6f050a029e
commit 776bba907c
3887 changed files with 59894 additions and 7280 deletions

View file

@ -1,29 +1,29 @@
import std.stdio, std.algorithm, std.metastrings, std.range;
import std.stdio, std.algorithm, std.range;
// iterative
long factorial(long n) {
long result = 1;
/// Iterative.
int factorial(in int n) {
int result = 1;
foreach (i; 1 .. n + 1)
result *= i;
return result;
}
// recursive
long recFactorial(long n) {
/// Recursive.
int recFactorial(in int n) {
if (n == 0)
return 1;
else
return n * recFactorial(n - 1);
}
// functional-style
long fact(long n) {
return iota(1, n + 1).reduce!q{a * b}();
/// Functional-style.
int fact(in int n) {
return iota(1, n + 1).reduce!q{a * b};
}
// tail recursive (at run-time, with DMD)
long tfactorial(long n) {
static long facAux(long n, long acc) {
/// Tail recursive (at run-time, with DMD).
int tfactorial(in int n) {
static int facAux(int n, int acc) {
if (n < 1)
return acc;
else
@ -32,16 +32,16 @@ long tfactorial(long n) {
return facAux(n, 1);
}
// computed and printed at compile-time
pragma(msg, toStringNow!(factorial(15)));
pragma(msg, toStringNow!(recFactorial(15)));
pragma(msg, toStringNow!(fact(15)));
pragma(msg, toStringNow!(tfactorial(15)));
// Computed and printed at compile-time.
pragma(msg, 15.factorial);
pragma(msg, 15.recFactorial);
pragma(msg, 15.fact);
pragma(msg, 15.tfactorial);
void main() {
// computed and printed at run-time
writeln(factorial(15));
writeln(recFactorial(15));
writeln(fact(15));
writeln(tfactorial(15));
// Computed and printed at run-time.
15.factorial.writeln;
15.recFactorial.writeln;
15.fact.writeln;
15.tfactorial.writeln;
}