Re: Proc and lambda

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

myfun = lambda { |x,y| x+y },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
time the lambda was defined (closures) - they remain alive, even though
have since dropped out of scope.

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

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
call, as it remembers a different value for n. Hence each one is a

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
(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
computer-science ways of thinking about functions:

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

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

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,
was easier to make sense of what was happening in LISP, Erlang etc.



P.S. If you’re asking for the difference between Proc and lambda, that’s
more awkward question, and one of the ugliest warts of Ruby. See

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