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.
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 occurn + 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