Class: Rumonade::PartialFunction

Inherits:
Proc
  • Object
show all
Defined in:
lib/rumonade/error_handling.rb

Overview

A partial function is a unary function where the domain does not necessarily include all values. The function #defined_at? allows to test dynamically if a value is in the domain of the function.

NOTE: This is only here to mimic the Scala library just enough to allow a close translation of the exception handling functionality. It’s not because I’m the sort that just loves pure functional idioms so damn much for their own sake. Just FYI.

Instance Method Summary collapse

Constructor Details

#initialize(defined_at_proc, call_proc) ⇒ PartialFunction

Returns a new instance of PartialFunction.



12
13
14
15
# File 'lib/rumonade/error_handling.rb', line 12

def initialize(defined_at_proc, call_proc)
  super(call_proc)
  @defined_at_proc = defined_at_proc
end

Instance Method Details

#and_then(func) ⇒ PartialFunction

Composes this partial function with a transformation function that gets applied to results of this partial function.

Parameters:

  • func (Proc)

    the transformation function

Returns:

  • (PartialFunction)

    a partial function with the same domain as this partial function, which maps arguments x to func.call(self.call(x)).



40
41
42
# File 'lib/rumonade/error_handling.rb', line 40

def and_then(func)
  PartialFunction.new(@defined_at_proc, lambda { |x| func.call(self.call(x)) })
end

#defined_at?(x) ⇒ Boolean

Checks if a value is contained in the function’s domain.

Parameters:

  • x

    the value to test

Returns:

  • (Boolean)

    Returns true, iff x is in the domain of this function, false otherwise.



20
21
22
# File 'lib/rumonade/error_handling.rb', line 20

def defined_at?(x)
  @defined_at_proc.call(x)
end

#or_else(other) ⇒ PartialFunction

Composes this partial function with a fallback partial function which gets applied where this partial function is not defined.

Parameters:

Returns:

  • (PartialFunction)

    a partial function which has as domain the union of the domains of this partial function and other. The resulting partial function takes x to self.call(x) where self is defined, and to other.call(x) where it is not.



30
31
32
33
# File 'lib/rumonade/error_handling.rb', line 30

def or_else(other)
  PartialFunction.new(lambda { |x| self.defined_at?(x) || other.defined_at?(x) },
                      lambda { |x| if self.defined_at?(x) then self.call(x) else other.call(x) end })
end