Logo

Programming-Idioms

  • JS
  • Rust

Idiom #31 Recursive factorial (simple)

Create the recursive function f which returns the factorial of the non-negative integer i, calculated from f(i-1)

fn factorial(num: u64) -> u64 {
    match num {
        0 | 1 => 1,
        _ => factorial(num - 1) * num,
    }
}

match arm for 0|1 checks if the numbers are either 0 or 1
fn f(n: u32) -> u32 {
    if n < 2 {
        1
    } else {
        n * f(n - 1)
    }
}
const f = i => i === 0 ? 1 : i * f(i-1)
function f(i) {
   return i<2 ? 1 : i * f(i-1);
}
function F (I : Natural) return Natural is (if I < 2 then 1 else I * F (I - 1));

New implementation...
< >
programming-idioms.org