Module: FunctionalRuby

Included in:
Method, Proc
Defined in:
lib/functional-ruby.rb

Instance Method Summary collapse

Instance Method Details

#+(f) ⇒ Object

Example

f = -> x { x * x }
g = -> x { x + 1 }
(f + g)[3] #=> 13


82
83
84
# File 'lib/functional-ruby.rb', line 82

def +(f)
  -> *args { self[*args] + f[*args] }
end

#-(f) ⇒ Object

Example

f = -> x { x * x }
g = -> x { x + 1 }
(f - g)[3] #=> 5


91
92
93
# File 'lib/functional-ruby.rb', line 91

def -(f)
  -> *args { self[*args] - f[*args] }
end

#/(f) ⇒ Object

Example

f = -> x { x * x }
g = -> x { x + 1 }
(f / g)[3] #=> 2


100
101
102
# File 'lib/functional-ruby.rb', line 100

def /(f)
  -> *args { self[*args] / f[*args] }
end

#apply_head(*first) ⇒ Object Also known as: >>, %

Example

pow = -> x, y { x ** y }
(pow >> 2)[3] #=> 8


6
7
8
# File 'lib/functional-ruby.rb', line 6

def apply_head(*first)
  -> *rest { self[*first.concat(rest)] }
end

#apply_tail(*last) ⇒ Object Also known as: <<

Example

pow = -> x, y { x ** y }
(pow % 2)[3] #=> 9


17
18
19
# File 'lib/functional-ruby.rb', line 17

def apply_tail(*last)
  -> *rest { self[*rest.concat(last)] }
end

#compose(f) ⇒ Object Also known as: *

Example

f = -> x { x * x }
g = -> x { x + 1 }
(f * g)[3] #=> 16


28
29
30
31
32
33
34
# 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

#map(enum) ⇒ Object Also known as: |

Example

f = -> x { x * x }
d = [1, 2, 3]
f | d #=> [1, 4, 9]


43
44
45
# File 'lib/functional-ruby.rb', line 43

def map(enum)
  enum.to_enum.map &self
end

#memoizeObject Also known as: +@

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


65
66
67
68
69
70
71
72
73
# File 'lib/functional-ruby.rb', line 65

def memoize
  cache = {}

  -> *args do
    cache.fetch(args) do
      cache[args] = self[*args]
    end
  end
end

#mult(f) ⇒ Object

Example

f = -> x { x * x }
g = -> x { x + 1 }
f.mult(g)[5] #=> 36


109
110
111
# File 'lib/functional-ruby.rb', line 109

def mult(f)
  -> *args { self[*args] * f[*args] }
end

#reduce(enum) ⇒ Object Also known as: <=

Example

f = -> a, e { a * e }
d = [1, 2, 3]
f <= d #=> 6


54
55
56
# File 'lib/functional-ruby.rb', line 54

def reduce(enum)
  enum.to_enum.reduce &self
end