Skip to content

Instantly share code, notes, and snippets.

@Albertoimpl
Created November 26, 2015 14:54
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 Albertoimpl/1bc5fe6f30653c4fbf58 to your computer and use it in GitHub Desktop.
Save Albertoimpl/1bc5fe6f30653c4fbf58 to your computer and use it in GitHub Desktop.
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