Module: Tins::PartialApplication
- Defined in:
- lib/tins/partial_application.rb
Overview
A module that provides partial application functionality.
This module is designed to be included in classes that respond to ‘call` and have an `arity` method. It’s commonly used with Proc and Method objects, but can be included in any class that implements the required interface.
Partial application allows you to create new callables by fixing some arguments of an existing callable, resulting in a callable with fewer parameters.
Class Method Summary collapse
-
.included(modul) ⇒ Object
Callback invoked when this module is included in a class.
Instance Method Summary collapse
-
#partial(*args) ⇒ Proc
Creates a partial application of the current object.
Class Method Details
.included(modul) ⇒ Object
Callback invoked when this module is included in a class. Overrides the ‘arity` method to support custom arity values for partial applications.
This is particularly useful for Proc and Method objects where the arity needs to be adjusted after partial application.
35 36 37 38 39 40 41 42 43 44 45 46 47 |
# File 'lib/tins/partial_application.rb', line 35 def self.included(modul) modul.module_eval do old_arity = instance_method(:arity) define_method(:arity) do if defined?(@__arity__) @__arity__ else old_arity.bind(self).call end end end super end |
Instance Method Details
#partial(*args) ⇒ Proc
Creates a partial application of the current object.
If no arguments are provided, returns a duplicate of the current object. If more arguments are provided than the object’s arity, raises an ArgumentError. Otherwise, creates a new lambda that combines the provided arguments with additional arguments when called.
This method is particularly useful for creating curried functions or partially applied methods where some parameters are pre-filled.
78 79 80 81 82 83 84 85 86 87 88 |
# File 'lib/tins/partial_application.rb', line 78 def partial(*args) if args.empty? dup elsif args.size > arity raise ArgumentError, "wrong number of arguments (#{args.size} for #{arity})" else f = lambda { |*b| call(*(args + b)) } f.instance_variable_set :@__arity__, arity - args.size f end end |