File: partial_application.rb

package info (click to toggle)
ruby-tins 1.32.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,248 kB
  • sloc: ruby: 6,659; makefile: 3
file content (31 lines) | stat: -rw-r--r-- 859 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
module Tins
  module PartialApplication
    # If this module is included into a Proc (or similar object), it tampers
    # with its Proc#arity method.
    def self.included(modul)
      modul.module_eval do
        old_arity = instance_method(:arity)
        define_method(:arity) do
          defined?(@__arity__) or old_arity.bind(self).call
        end
      end
      super
    end

    # Create a partial application of this Proc (or similar object) using
    # _args_ as the already applied arguments.
    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
  end
end

require 'tins/alias'