module FunctionalRuby

Public Instance Methods

%(*first)
Alias for: apply_head
*(f)
Alias for: compose
+(f) click to toggle source

Example

f = -> x { x * x }
g = -> x { x + 1 }
(f + g)[3] #=> 13
# File lib/functional-ruby.rb, line 82
def +(f)
  -> *args { self[*args] + f[*args] }
end
+@()
Alias for: memoize
-(f) click to toggle source

Example

f = -> x { x * x }
g = -> x { x + 1 }
(f - g)[3] #=> 5
# File lib/functional-ruby.rb, line 91
def -(f)
  -> *args { self[*args] - f[*args] }
end
/(f) click to toggle source

Example

f = -> x { x * x }
g = -> x { x + 1 }
(f / g)[3] #=> 2
# File lib/functional-ruby.rb, line 100
def /(f)
  -> *args { self[*args] / f[*args] }
end
<<(*last)
Alias for: apply_tail
<=(enum)
Alias for: reduce
>>(*first)
Alias for: apply_head
apply_head(*first) click to toggle source

Example

pow = -> x, y { x ** y }
(pow >> 2)[3] #=> 8
# File lib/functional-ruby.rb, line 6
def apply_head(*first)
  -> *rest { self[*first.concat(rest)] }
end
Also aliased as: >>, %
apply_tail(*last) click to toggle source

Example

pow = -> x, y { x ** y }
(pow % 2)[3] #=> 9
# File lib/functional-ruby.rb, line 17
def apply_tail(*last)
  -> *rest { self[*rest.concat(last)] }
end
Also aliased as: <<
compose(f) click to toggle source

Example

f = -> x { x * x }
g = -> x { x + 1 }
(f * g)[3] #=> 16
# File lib/functional-ruby.rb, line 28
def compose(f)
  if respond_to? :arity and arity == 1
    -> *args { self[f[*args]] }
  else
    -> *args { self[*f[*args]] }
  end
end
Also aliased as: *
map(enum) click to toggle source

Example

f = -> x { x * x }
d = [1, 2, 3]
f | d #=> [1, 4, 9]
# File lib/functional-ruby.rb, line 43
def map(enum)
  enum.to_enum.map &self
end
Also aliased as: |
memoize() click to toggle source

Example

fact = +-> n { n < 2 ? 1 : n * fact[n - 1] }
t = Time.now; fact[1000]; Time.now - t #=> 0.018036605
t = Time.now; fact[1000]; Time.now - t #=> 2.6761e-05
# File lib/functional-ruby.rb, line 65
def memoize
  cache = {}

  -> *args do
    cache.fetch(args) do
      cache[args] = self[*args]
    end
  end
end
Also aliased as: +@
mult(f) click to toggle source

Example

f = -> x { x * x }
g = -> x { x + 1 }
f.mult(g)[5] #=> 36
# File lib/functional-ruby.rb, line 109
def mult(f)
  -> *args { self[*args] * f[*args] }
end
reduce(enum) click to toggle source

Example

f = -> a, e { a * e }
d = [1, 2, 3]
f <= d #=> 6
# File lib/functional-ruby.rb, line 54
def reduce(enum)
  enum.to_enum.reduce &self
end
Also aliased as: <=
|(enum)
Alias for: map