Created
November 26, 2015 14:54
-
-
Save Albertoimpl/1bc5fe6f30653c4fbf58 to your computer and use it in GitHub Desktop.
Ruby enabling tail recursion
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
RubyVM::InstructionSequence.compile_option = { | |
tailcall_optimization: true, | |
trace_instruction: false | |
} | |
eval <<END | |
def factorial_tailcall(n, accumulated=1) | |
return accumulated if n <= 1 | |
factorial_tailcall(n - 1, n * accumulated) | |
end | |
def factorial_recursive(n) | |
return 1 if n <= 1 | |
n * factorial_recursive(n - 1) | |
end | |
def factorial_iterative(n) | |
accumulated = 1 | |
while n > 1 | |
accumulated = n * accumulated | |
n = n - 1 | |
end | |
accumulated | |
end | |
END |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment