Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

added #and_then to PartialFunction

  • Loading branch information...
commit a2e8adc1fd3c17a107d56289b2e1345c44917734 1 parent 353faca
@ms-ati authored
Showing with 22 additions and 0 deletions.
  1. +9 −0 lib/rumonade/error_handling.rb
  2. +13 −0 test/error_handling_test.rb
View
9 lib/rumonade/error_handling.rb
@@ -31,6 +31,15 @@ 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
+
+ # Composes this partial function with a transformation function that
+ # gets applied to results of this partial function.
+ # @param [Proc] func the transformation function
+ # @return [PartialFunction] a partial function with the same domain as this partial function, which maps
+ # arguments +x+ to +func.call(self.call(x))+.
+ def and_then(func)
+ PartialFunction.new(@defined_at_proc, lambda { |x| func.call(self.call(x)) })
+ end
end
# Classes representing the components of exception handling.
View
13 test/error_handling_test.rb
@@ -18,4 +18,17 @@ def test_partial_function_or_else_returns_a_partial_function_with_union_of_defin
assert !pf.defined_at?(5000)
assert pf.defined_at?(5001)
end
+
+ def test_partial_function_or_else_returns_a_partial_function_with_fallback_when_outside_defined_at
+ pf = PartialFunction.new(lambda { |x| x < 1000 }, lambda { |x| x * 10 })
+ .or_else(PartialFunction.new(lambda { |x| x > 5000 }, lambda { |x| x / 5 }))
+ assert_equal 9990, pf.call(999)
+ assert_equal 1001, pf.call(5005)
+ end
+
+ def test_partial_function_and_then_returns_a_partial_function_with_func_called_on_result_of_pf_call
+ pf = PartialFunction.new(lambda { |x| x < 1000 }, lambda { |x| x * 10 })
+ .and_then(lambda { |x| x / 5 })
+ assert_equal 1800, pf.call(900)
+ end
end
Please sign in to comment.
Something went wrong with that request. Please try again.