Last active
December 20, 2015 10:59
-
-
Save afiore/6120093 to your computer and use it in GitHub Desktop.
Better currying for Ruby Proc objects
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Proc | |
def _(*args) | |
CurriedProc.new(args, &self) | |
end | |
end | |
class CurriedProc < Proc | |
def initialize(args, &block) | |
msg = "Curried arguments is greater than block arity (#{args.size} > #{block.arity})" | |
raise ArgumentError, msg if args.size > block.arity | |
@curried_args = args | |
@orig_arity = block.arity | |
@orig_proc = block | |
end | |
def arity | |
@orig_arity - @curried_args.size | |
end | |
def call(*args) | |
msg = "Wrong number of arguments (#{args.size} of #{arity}) - curried" | |
raise ArgumentError, msg if args.size > arity | |
new_args = @curried_args + args.take(arity) | |
@orig_proc.call(*new_args) | |
end | |
def _(*args) | |
self.class.new(@curried_args + args, &@orig_proc) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment