Class: Functor

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

Defined Under Namespace

Modules: Method

Instance Method Summary collapse

Constructor Details

#initialize {|_self| ... } ⇒ Functor

Returns a new instance of Functor.

Yields:

  • (_self)

Yield Parameters:

  • _self (Functor)

    the object that the method was called on



33
34
35
# File 'lib/functor.rb', line 33

def initialize( &block )
  @rules = [] ; yield( self ) if block_given?
end

Instance Method Details

#[](*args, &block) ⇒ Object



49
50
51
# File 'lib/functor.rb', line 49

def []( *args, &block )
  call( *args, &block )
end

#call(*args, &block) ⇒ Object



45
46
47
# File 'lib/functor.rb', line 45

def call( *args, &block )
  match( *args, &block ).call( *args )
end

#given(*pattern, &action) ⇒ Object



41
42
43
# File 'lib/functor.rb', line 41

def given( *pattern, &action )
  @rules << [ pattern, action ]
end

#initialize_copy(from) ⇒ Object



37
38
39
# File 'lib/functor.rb', line 37

def initialize_copy( from )
  @rules = from.instance_eval { @rules.clone }
end

#match(*args, &block) ⇒ Object



55
56
57
58
59
60
# File 'lib/functor.rb', line 55

def match( *args, &block )
  args << block if block_given?
  pattern, action = @rules.reverse.find { | p, a | match?( args, p ) }
  action or 
    raise ArgumentError.new( "Argument error: no functor matches the given arguments." )
end

#to_procObject



53
# File 'lib/functor.rb', line 53

def to_proc ; lambda { |*args| self.call( *args ) } ; end