Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Ruby

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)

f = Hash.new { |hash, i| hash[i] = i * hash[i -1] }
f[0] = 1

Note that f is not a function but plain old Hash used as a cache for performance.
fac = Hash.new {|h, i| h[i] = i * h[i-1] }.tap {|h| h[0] = 1 }
function F (I : Natural) return Natural is (if I < 2 then 1 else I * F (I - 1));

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