Ad

This illustrates how to sum natural numbers using tail recursion. In some languages, tail call optimization is performed, which enables recursive calls to take constant stack space.

Code
Diff
  • def sum n
        def acc(n, s)
            return s if n <= 0 # Base case
            acc(n - 1, s + n)  # Recursion step, with accumulator
        end
        acc(n, 0)
    end
    • def sum n
    • return 1 if n == 1 # Base case of recursion method - must be defined; otherwise infinite recursion may occur
    • n + sum(n - 1)
    • def acc(n, s)
    • return s if n <= 0 # Base case
    • acc(n - 1, s + n) # Recursion step, with accumulator
    • end
    • acc(n, 0)
    • end