# Re: Proc and lambda

**URL:** <https://www.ruby-forum.com/t/re-proc-and-lambda/147217>\
**Category:** Ruby\
**Created:** [August 29, 2008, 1:22pm UTC](https://www.ruby-forum.com/t/re-proc-and-lambda/147217 "2008-08-29T13:22:35Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![stickstone](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/6f9a4e/32.png) [@stickstone](https://www.ruby-forum.com/u/stickstone)\
**Post date:** [August 29, 2008, 1:22pm UTC](https://www.ruby-forum.com/t/re-proc-and-lambda/147217/1 "2008-08-29T13:22:35Z")

</div>

> 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](http://innig.net/software/ruby/closures-in-ruby.rb)
