Skip to content

Instantly share code, notes, and snippets.

@remcopeereboom
Created February 20, 2015 14:40
Show Gist options
  • Save remcopeereboom/4efb34feb568f3e2c81e to your computer and use it in GitHub Desktop.
Save remcopeereboom/4efb34feb568f3e2c81e to your computer and use it in GitHub Desktop.
Enabling tail recursion in ruby
require_relative 'tail_call_optimization' # All files loaded AFTER this file with have tail-recursion enabled.
require_relative 'tail_factorial'
def factorial(n, acc = 1)
return acc if n <= 1
factorial(n - 1, n * acc)
end
puts factorial(10000)
# Enable recursion GLOBALLY --> See my GitHub to do it locally (the right way).
RubyVM::InstructionSequence.compile_option = {
:tailcall_optimization => true,
:trace_instruction => false
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment