Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Function composition in Ruby

256 views
Skip to first unread message

Tom Moertel

unread,
Apr 7, 2006, 12:29:27 PM4/7/06
to
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

Vincent Foley

unread,
Apr 7, 2006, 2:11:08 PM4/7/06
to
Yep. That's why the fine Ruby Facets folks decided to use it :)
http://facets.rubyforge.org/doc/api/core/classes/Proc.html#M000146

Have a nice week end!

Tom Moertel

unread,
Apr 7, 2006, 3:10:45 PM4/7/06
to
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

0 new messages