Skip to content

Instantly share code, notes, and snippets.

@marianposaceanu
Last active November 16, 2015 19:24
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 marianposaceanu/c66e846f6b62d4345612 to your computer and use it in GitHub Desktop.
Save marianposaceanu/c66e846f6b62d4345612 to your computer and use it in GitHub Desktop.
run_with_tco = ARGV.include?('-TCO')
# Force the ruby interpreter to use TCO
RubyVM::InstructionSequence.compile_option = {
tailcall_optimization: true,
trace_instruction: false
} if run_with_tco
puts 'To infinity and beyond!' if run_with_tco
HEADFULL_HORSE = 0.3
HEADLESS_HORSE = 0.7
HORSE = HEADLESS_HORSE + HEADFULL_HORSE
RubyVM::InstructionSequence.new(<<-EOS).eval
# "A centaur that's half horse and half centaur" => ?
# the tail recursive version
def centaur(horse:, divider:)
return horse/divider if horse < 0
centaur(horse: horse, divider: divider*2)
end
EOS
# "A centaur that's half horse and half centaur"
puts centaur(horse: HORSE/2, divider: 2)

Without TCO

➜  half_half_tco  ruby half_half.rb
<compiled>:4:in `centaur': stack level too deep (SystemStackError)
	from <compiled>:6:in `centaur'
	from <compiled>:6:in `centaur'
	from <compiled>:6:in `centaur'
	from <compiled>:6:in `centaur'
	from <compiled>:6:in `centaur'
	from <compiled>:6:in `centaur'
	from <compiled>:6:in `centaur'
	from <compiled>:6:in `centaur'
	 ... 8177 levels...
	from <compiled>:6:in `centaur'
	from <compiled>:6:in `centaur'
	from <compiled>:6:in `centaur'
	from half_half.rb:25:in `<main>'

With TCO

➜  half_half_tco  ruby half_half.rb -TCO
To infinity and beyond!
@marianposaceanu
Copy link
Author

note it all started from here:

screen shot 2015-11-16 at 21 07 16

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment