Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Higher Order Functions in Ruby

I'm trying to learn Ruby right now after learning Python and I'm having trouble translating this code to Ruby:

def compose1(f, g):
    """Return a function h, such that h(x) = f(g(x))."""
    def h(x):
        return f(g(x))
return h

Do I have to translate this using blocks? Or is there a similar syntax in Ruby?

like image 993
etabelet Avatar asked Dec 18 '12 19:12

etabelet


1 Answers

You can do this with lambdas in Ruby (I'm using the 1.9 stabby-lambda here):

compose = ->(f,g) { 
  ->(x){ f.(g.(x)) }  
}

So compose is a function that returns another function, as in your example:

f = ->(x) { x + 1 }
g = ->(x) { x * 3 }

h = compose.(f,g)
h.(5) #=> 16

Note that functional programming is not really Ruby's strong suit - it can be done but it looks a bit messy in my opinion.

like image 169
Zach Kemp Avatar answered Oct 03 '22 14:10

Zach Kemp