[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Function composition in Ruby

Tom Moertel

4/7/2006 4:29:00 PM

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

2 Answers

Vincent Foley

4/7/2006 6:11:00 PM

0

Yep. That's why the fine Ruby Facets folks decided to use it :)
http://facets.rubyforge.org/doc/api/core/classes/Proc.ht...

Have a nice week end!

Tom Moertel

4/7/2006 7:11:00 PM

0

Vincent Foley wrote:
> Yep. That's why the fine Ruby Facets folks decided to use it :)

You know, there's a lesson in there somewhere. ;-)

Cheers,
Tom