Skip to content

Instantly share code, notes, and snippets.

@tenderlove
Created April 1, 2012 23:21
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save tenderlove/2279384 to your computer and use it in GitHub Desktop.
Save tenderlove/2279384 to your computer and use it in GitHub Desktop.
require 'minitest/autorun'
###
# Test to demonstrate TCO in Ruby. Tested in 1.9.2+
class TestTCO < MiniTest::Unit::TestCase
code = <<-eocode
class Facts
def fact_helper(n, res)
if n == 1
res
else
fact_helper(n - 1, n * res)
end
end
def fact(n)
fact_helper(n, 1)
end
end
eocode
eval code
RubyVM::InstructionSequence.compile_option = {
:tailcall_optimization => true,
:trace_instruction => false
}
# Any code you want with TCO should happen after you've tweaked compile_option
eval code.sub(/Facts/, 'TCOFacts')
FACTSIZE = 30_000
def test_exception
assert_raises(SystemStackError) do
Facts.new.fact(FACTSIZE)
end
end
def test_tco
assert TCOFacts.new.fact(FACTSIZE)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment