Created
May 21, 2020 06:28
-
-
Save mrk21/73dd5eedf2210969284754b14913d467 to your computer and use it in GitHub Desktop.
Tail call optimization for Ruby
This file contains hidden or 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
# @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