Created
April 1, 2012 23:21
-
-
Save tenderlove/2279384 to your computer and use it in GitHub Desktop.
This file contains 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
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