Skip to content

Instantly share code, notes, and snippets.

@yanmhlv
Created March 9, 2014 12:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yanmhlv/9447037 to your computer and use it in GitHub Desktop.
Save yanmhlv/9447037 to your computer and use it in GitHub Desktop.
functional module
module Functional
def apply(enum)
enum.map &self
end
alias | apply
def reduce(enume)
enum.inject &self
end
alias <= reduce
def compose(f)
if self.respond_to?(:arity) && self.arity == 1
lambda {|*args| self[f[*args]]}
else
lambda {|*args| self[*f[*args]]}
end
alias * compose
end
def apply_head(*first)
lambda {|*rest| self[*first.concat(rest)]}
end
def apply_tail(*last)
lambda {|*rest| self[*rest.concat(last)]}
end
alias >> apply_head
alias << apply_tail
def memoize
cache = {}
lambda do |*args|
unless cache.has_key(args)
cache[args] = self[*args]
end
cache[args]
end
end
alias +@ memoize
end
class Proc; include Functional; end
class Method; include Functional; end
class Symbol
def to_proc
lambda {|receiver, *args| receiver.method(self)[*args]}
end
def [](obj)
obj.method(self)
end
def []=(o, f)
sym = self
eigenclass.instance_eval {define_method(sym, f)}
end
end
class Module
alias [] instance_method
end
# class UnboundMethod
# alias [] bind
# end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment