Logo

Programming-Idioms

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

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)

type
  TPositiveInt = 0..MaxInt;

function _f(_i: TPositiveInt): Integer;
begin
  if (_i < 2) then
    Result := 1
  else
    Result := _f(_i - 1);
end; 

The definition of type TPositiveInt allows for rangechecking on the input.
MaxInt is already defined in the language.
function F (I : Natural) return Natural is (if I < 2 then 1 else I * F (I - 1));

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