module Functional::Memo::ClassMethods

@!visibility private

Attributes

__method_memos__[RW]

@!visibility private

Public Instance Methods

__define_memo_proxy__(func) click to toggle source

@!visibility private

# File lib/functional/memo.rb, line 82
      def __define_memo_proxy__(func)
        self.class_eval <<-RUBY
          def self.#{func}(*args, &block)
            self.__proxy_memoized_method__(:#{func}, *args, &block)
          end
        RUBY
      end
__proxy_memoized_method__(func, *args, &block) click to toggle source

@!visibility private

# File lib/functional/memo.rb, line 91
def __proxy_memoized_method__(func, *args, &block)
  memo = self.__method_memos__[func]
  memo.synchronize do
    if block_given?
      memo.function.call(*args, &block)
    elsif memo.cache.has_key?(args)
      memo.cache[args]
    else
      result = memo.function.call(*args)
      memo.cache[args] = result unless memo.max_cache?
    end
  end
end
memoize(func, opts = {}) click to toggle source

Returns a memoized version of a referentially transparent function. The memoized version of the function keeps a cache of the mapping from arguments to results and, when calls with the same arguments are repeated often, has higher performance at the expense of higher memory use.

@param [Symbol] func the class/module function to memoize @param [Hash] opts the options controlling memoization @option opts [Fixnum] :at_most the maximum number of memos to store in

the cache; a value of zero (the default) or `nil` indicates no limit

@raise [ArgumentError] when the method has already been memoized @raise [ArgumentError] when :at_most option is a negative number

# File lib/functional/memo.rb, line 71
def memoize(func, opts = {})
  func = func.to_sym
  max_cache = opts[:at_most].to_i
  raise ArgumentError.new("method :#{func} has already been memoized") if __method_memos__.has_key?(func)
  raise ArgumentError.new(':max_cache must be > 0') if max_cache < 0
  __method_memos__[func] = Memoizer.new(method(func), max_cache.to_i)
  __define_memo_proxy__(func)
  nil
end