Function composition in Ruby

T

Tom Moertel

Is it just me, or does the star operator (*) not make a perfect choice
for function composition?

class Proc
def self.compose(f, g)
lambda { |*args| f[g[*args]] }
end
def *(g)
Proc.compose(self, g)
end
end

inc = lambda { |x| x + 1 }
thrice = lambda { |x| 3 * x }

thrice_of_inc = thrice * inc
thrice_of_inc[1]
=> 6

twice_of_dec = lambda { |x| 2 * x } * lambda { |x| x - 1 }
twice_of_dec[3]
=> 4

thrice_of_inc_of_thrice = thrice * inc * thrice
thrice_of_inc_of_thrice[1]
=> 12

It almost feels as if it were meant to be that way. ;-)
I love Ruby.

Cheers,
Tom
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top