Skip to content

Instantly share code, notes, and snippets.

@mrk21
Created May 21, 2020 06:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrk21/73dd5eedf2210969284754b14913d467 to your computer and use it in GitHub Desktop.
Save mrk21/73dd5eedf2210969284754b14913d467 to your computer and use it in GitHub Desktop.
Tail call optimization for Ruby
# @see [Rubyの末尾呼び出し最適化を試す - Qiita](https://qiita.com/rsnni/items/8f818f2c2da07896fc7e)
RubyVM::InstructionSequence.compile_option = {
:tailcall_optimization => true,
:trace_instruction => false
}
RubyVM::InstructionSequence.new(<<-EOS).eval
def fact(x)
return 1 if x == 0
fact(x - 1) * x
end
def fact_tail_call(x, m = 1)
return m if x == 0
fact_tail_call(x - 1, x * m)
end
EOS
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment