Last active
August 29, 2015 14:18
-
-
Save sfcgeorge/4b9d26073c28ba3dc66d to your computer and use it in GitHub Desktop.
MRI Ruby optional tail call optimization
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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