Class: Functor

Inherits:
Object show all
Defined in:
lib/core/facets/functor.rb

Overview

Functor is Ruby's implementation of a Higher-Order-Message. Essentally, a Functor can vary its behavior accorrding to the operation applied to it.

Example

f = Functor.new { |op, x| x.send(op, x) }
(f + 1)  #=> 2
(f + 2)  #=> 4
(f + 3)  #=> 6
(f * 1)  #=> 1
(f * 2)  #=> 4
(f * 3)  #=> 9

Constant Summary collapse

EXCEPTIONS =
[:binding, :inspect, :object_id]

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(&function) ⇒ Functor


66
67
68
# File 'lib/core/facets/functor.rb', line 66

def initialize(&function)
  @function = function
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(op, *args, &blk) ⇒ Object (private)

Any action against the Functor is processesd by the function.


88
89
90
# File 'lib/core/facets/functor.rb', line 88

def method_missing(op, *args, &blk)
  @function.call(op, *args, &blk)
end

Class Method Details

.cache(*key, &function) ⇒ Object

Functors can be somewhat inefficient if a new Functor is frequently recreated for the same use. So this cache can be used to speed things up.

The key will always be an array, wich makes it easier to cache Functor for multiple factors.


23
24
25
26
27
28
29
30
# File 'lib/core/facets/functor.rb', line 23

def self.cache(*key, &function)
  @cache ||= {}
  if function
    @cache[key] = new(&function)
  else
    @cache[key]
  end
end

Instance Method Details

#to_procObject


71
72
73
# File 'lib/core/facets/functor.rb', line 71

def to_proc
  @function
end