Philip Cunningham music, code and stuff.

Ribitco: Noddy runtime TCO for Ruby 05 January 2013

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.

Installation

Add this line to your application's Gemfile:

gem 'ribitco'

And then execute:

$ bundle

Or install it yourself as:

$ gem install ribitco

This Code

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

Becomes

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...