Re: Proc and lambda

Is there any super easy explanation or tutorial for proc and lamda?

myfun = lambda { |x,y| x+y }

myfun.call(3,4) #=> 7
myfun[3,4] #alternative syntax

Can’t get much easier than that really.

The interesting bit comes when you bind to variables which existed at
the
time the lambda was defined (closures) - they remain alive, even though
they
have since dropped out of scope.

def make_adder(n)
lambda { |x| n+x }
end

inc = make_adder(1)
addtwo = make_adder(2)

inc[5] #=> 6
addtwo[8] #=> 10

make_adder returns a lambda, and it is returning a different one from
each
call, as it remembers a different value for n. Hence each one is a
separate
object.

But there’s no need for ‘def’: one lambda can return another. So we can
rewrite that as:

add = lambda { |x| lambda { |y| x+y } }
add[4][5] #=> 9
inc = add[1]
inc[5] #=> 6

Computer scientists would call that particular example “currying” I
believe
(demonstrating how a function which takes multiple arguments can be
rewritten as functions which take a single argument).

That’s about it really. But once you’ve grasped that, you can try some
more
computer-science ways of thinking about functions:

fact = lambda { |n| n < 2 ? 1 : n*fact[n-1] }
fact[10]

fact2 = lambda { |n,t| n < 2 ? t : fact2[n-1, t*n] }
fact2[10,1]

Unfortunately this is just a plaything in Ruby, since it doesn’t support
tail recursion. fact2[10000,1] bombs out on my machine.

Do I need experience with Lisp or Smalltalk?

No, not really. I found the opposite: once I “got” the concepts in Ruby,
it
was easier to make sense of what was happening in LISP, Erlang etc.

Regards,

Brian.

P.S. If you’re asking for the difference between Proc and lambda, that’s
a
more awkward question, and one of the ugliest warts of Ruby. See
http://innig.net/software/ruby/closures-in-ruby.rb

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs