Lambda composition in ruby
In order to be able to compose lambdas like in other functional languages we need to add a simple method to Proc class.
class Proc
def *(f)
->(*args) { self.(f.(*args)) }
end
end
Now we can do:
plus2 = ->(n) { n+2 }
plus3 = ->(n) { n+3 }
plus5 = plus2 * plus3
plus5.(5) # returns 10
Note that notation f.(x) if exactly the same as f.call(x). It's just a bit shorter.
Written by Matjaz Muhic
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Ruby
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#