tags:

views:

358

answers:

4

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

+10  A: 

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
DigitalRoss
thanks a lot, that cleared my doubts.
burlsm
A: 

Here is a pretty nice screen-cast explaining blocks and closures in Ruby: http://www.teachmetocode.com/screencasts/8

Oliver Kiel
i'll take a look at the video, thanks
burlsm
+2  A: 

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.

jleedev
A: 

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
Michael Kohl