Friday, February 1, 2008

Ruby: Trivial Memoisation with Hashes

Using the block form of ruby's Hash constructor makes memoisation really easy. Here's some code that does has a hash do recursive lookups upon itself. Pretty nifty, eh?

require 'logger'

logger = Logger.new($stdout)

fib = Hash.new {|fib, x|
  logger.debug "Calculating fib(#{x})..."
  fib[x] = if [1,2].include? x
    1
  else
    fib[x-1] + fib [x-2]
  end
}

puts fib[5]
puts fib[7]