Created
March 9, 2014 12:27
-
-
Save yanmhlv/9447037 to your computer and use it in GitHub Desktop.
functional module
This file contains 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
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