base case: This is a critical piece in order for recursion to run and not get "stack level too deep (SystemStackError)". The recursive function needs to know when to to stop and base case is the floor at which the recursive function stops. Think of this as a break if statement for recursive functions.
countdown: The countdown is simply counting with n - 1 until n reaches 0.
>> def countdown(n)
.. return if n.zero? # base case
.. puts n
.. countdown(n-1) # getting closer to base case
.. end #=> nil
>> countdown(5) #=> nil
5
4
3
2
1
The function below is a recursive factorial function. The base case for this is when n <= 1 and then the final value n is returned. What the function then does is multiply the integer given n by the function n - 1 and count down until n = 1.
def factorial_recursive(n)
return n if n <= 1
factorial_recursive( n - 1 ) * n
end
puts factorial_recursive(3)
No comments:
Post a Comment