Recursion

A common example of recursion is the factorial calculation. You can see that in action below:

def factorial(n)
  n == 0 ? 1 : n * factorial(n - 1)
end

p factorial(6) # => 720

The same recursive function can be made type safe, and can include guards for negative integers:

def factorial(n : Int32) : Int32
  if n < 0
    raise "Error, n cannot be negative"
  end
  n == 0 ? 1 : n * factorial(n - 1)
end

begin
  p factorial(6)  # => 720
  p factorial(-6) # => "Error, n cannot be negative"
rescue ex
  p ex.message
end

As discussed in the exception handling section, the begin-rescue call is rather expensive. For a better performance, you can just guard against the problem input by a plain if statement and an exit:

def factorial(n : Int32) : Int32
  if n < 0
    p "Error, n cannot be negative!"
    exit
  end
  n == 0 ? 1 : n * factorial(n - 1)
end

p factorial(6)  # => 720
p factorial(-6) # => "Error, n cannot be negative"

Of course, most of the time the exit statement will be an overkill, so you can just simply return from a problemlamitc input in a recursive function, preventing cases like infinite recursion.