Function composition in Ruby

Discussion in 'Ruby' started by Tom Moertel, Apr 7, 2006.

  1. Tom Moertel

    Tom Moertel Guest

    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
     
    Tom Moertel, Apr 7, 2006
    #1
    1. Advertising

  2. Vincent Foley, Apr 7, 2006
    #2
    1. Advertising

  3. Tom Moertel

    Tom Moertel Guest

    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
     
    Tom Moertel, Apr 7, 2006
    #3
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Alan G Isaac

    Pythonic function composition

    Alan G Isaac, Oct 25, 2004, in forum: Python
    Replies:
    6
    Views:
    452
    Lonnie Princehouse
    Oct 25, 2004
  2. Kay Schluehr
    Replies:
    10
    Views:
    608
    Kay Schluehr
    Feb 4, 2008
  3. Arnaud Delobelle

    An idea for fast function composition

    Arnaud Delobelle, Feb 16, 2008, in forum: Python
    Replies:
    4
    Views:
    345
  4. Edgardo Hames

    Defining a new function by composition

    Edgardo Hames, Aug 6, 2004, in forum: Ruby
    Replies:
    7
    Views:
    132
    Robert Klemme
    Aug 7, 2004
  5. Rui Maciel
    Replies:
    1
    Views:
    223
    Gert-Jan de Vos
    Apr 13, 2013
Loading...

Share This Page