Programming-Idioms

Implementation
D

Be concise.

Be useful.

All contributions dictatorially edited by webmasters to match personal tastes.

Please try to avoid dependencies to third-party libraries and frameworks.

Implementation edit is for fixing errors and enhancing with metadata.

Instead of changing the code of the snippet, consider creating another D implementation.

Other implementations
int f(int i){
if(i==0)
return 1;
else
return i * f(i-1);
}
def f(i):
if i == 0:
return 1
else:
return i * f(i-1)
sub f {
my \$n = shift;
return \$n<2 ? 1 : \$n * f(\$n-1);
}
function f(n) {
return n<2 ? 1 : n * f(n-1);
}
fn f(n: u32) -> u32 {
if n < 2 {
1
} else {
n * f(n - 1)
}
}
unsigned int f(unsigned int i)
{
return i?i*f(i-1):1;
}
type
TPositiveInt = 0..MaxInt;

function _f(_i: TPositiveInt): Integer;
begin
if (_i < 2) then
Result := 1
else
Result := _f(_i - 1);
end;
f(i) => (i == 0) ? 1 : i * f(i - 1);
f = Hash.new { |hash, i| hash[i] = i * hash[i -1] }
f[0] = 1
defmodule Factorial do
def of(0), do: 1
def of(n) when n > 0 do
n * of(n-1)
end
end
f i = if i > 1 then f (i-1) * i else 1
func f(i int) int {
if i == 0 {
return 1
}
return i * f(i-1)
}
f(0) -> 1;
f(I) -> I * f(I - 1).
function F (I : Natural) return Natural is (if I < 2 then 1 else I * F (I - 1));
unsigned int f( unsigned int i ) {
if ( i == 0 ) return 1;

return i * f( i - 1 )
}
function f(\$i) {
if(\$i == 0) {
return 1;
}

return (\$i * f(\$i-1));
}
function f(n)
local function f_(factorial,n)
if n < 2 then return 1
return f_(factorial*n, n-1)
end
return f_(1,n)
end
fac = Hash.new {|h, i| h[i] = i * h[i-1] }.tap {|h| h[0] = 1 }
(define (f i)
(if (> i 1)
(* (f (- i 1)) i)
1))
(defn f [i]
(loop [cnt i, acc 1N]
(if (zero? cnt) acc
(recur (dec cnt) (* cnt acc)))))
fn factorial(num: u64) -> u64 {
match num {
0 | 1 => 1,
_ => factorial(num - 1) * num,
}
}
private static int Factorial(int n) {
if (n == 0) return 1;
return n * Factorial(n - 1);
}
def f(i: Int): Int =
if (i > 1){
i * f(i-1)
} else{
1
}
function f(int \$i): int
{
if (\$i == 0) {
return 1;
}

return \$i * f(\$i - 1);
}
const fact = n => n === 0 ? 1 : n * fact(n-1)
(defun f (i)
(if (< i 2)
1
(* i (f (- i 1)))))
module x
implicit none
contains
recursive function fac (n) result (res)
integer, intent(in) :: n
integer :: res
if (n <= 0) then
res = 1
else
res = fac(n-1) * n
end if
end function fac
end module x
fun f(i: Int): Int = when (i) {
0 -> 1
else -> i * f(i - 1)
}
fun f(i: Int) = if (i == 0) 1 else i * f(i - 1)
unsigned f(unsigned i) {
return i?i*f(i-1):1;
}
def f(i) { i == 0 ? 1 : i * f(i - 1) }