Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Ruby enabling tail recursion
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