hi
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))
thanks in advance
hi
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))
thanks in advance
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
Here is a pretty nice screen-cast explaining blocks and closures in Ruby: http://www.teachmetocode.com/screencasts/8
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