Logo

Programming-Idioms

  • Smalltalk
  • Fortran

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)

module x
  implicit none
contains
  recursive function f (i) result (res)
    integer, intent(in) :: i
    integer :: res
    if (i <= 0) then
       res = 1
    else
       res = f(i-1) * i
    end if
  end function f
end module x
f := [:i | i = 0 ifTrue: [1] ifFalse: [i * (f value: i - 1)]].
function F (I : Natural) return Natural is (if I < 2 then 1 else I * F (I - 1));

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