So, I wrote my first RubyGem recently. It provides a class macro that allows you to tail-call optimise methods at runtime. Please note that this was just a bit of fun and I realise there are corner cases. The source code is available here.
Add this line to your application's Gemfile:
And then execute:
Or install it yourself as:
$ gem install ribitco
require 'ribitco' class Recursive def factorial(n, acc=1) if n < 2 then acc else factorial(n - 1, n * acc) end end include Ribitco::TailCallOptimiser tco :factorial end
class Recursive define_method :factorial do |n, acc = 1| (n < 2) ? (acc) : (n = (n - 1); acc = (n * acc); redo) end end
No Stack Explosion
example = Recursive.new puts example.factorial(10000) # => 284625968091705451890641321211986889014805140170...