Question
I'm having a little trouble with closures and I'd like to know what the equivalent code for the canonical make-adder procedure would be in Ruby.
In scheme it would be like:
(define (make-adder n)
(lambda (x) (+ x n))
Solution
It's actually very close...
def make_addr n
lambda { |x| x + n }
end
t = make_addr 100
t.call 1
101
In 1.9 you can use...
def make_addr n
->(x) { x + n }
end
OTHER TIPS
One difference is that while Scheme has only one kind of procedure, Ruby has four. Most of the time, they behave similarly enough to your standard lambda, but you should try to understand all the details in depth.
Here's another way to do it in 1.9:
make_adder = -> n, x { n + x }
hundred_adder = make_adder.curry[100]
hundred_adder[4] # => 104
Here is a pretty nice screen-cast explaining blocks and closures in Ruby: http://www.teachmetocode.com/screencasts/8
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow