Skip to content

Instantly share code, notes, and snippets.

@sfcgeorge
Last active August 29, 2015 14:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sfcgeorge/4b9d26073c28ba3dc66d to your computer and use it in GitHub Desktop.
Save sfcgeorge/4b9d26073c28ba3dc66d to your computer and use it in GitHub Desktop.
MRI Ruby optional tail call optimization
# Comment the below compile_options out and
# this will crash with stack level too deep.
# Based on http://timelessrepo.com/tailin-ruby
RubyVM::InstructionSequence.compile_option = {
tailcall_optimization: true,
trace_instruction: false
}
RubyVM::InstructionSequence.new(<<-CODE).eval
def factorial(n, result = 1)
return result if n <= 1
factorial(n - 1, n * result)
end
CODE
puts factorial(10_000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment