Where and when to use Lambda?

2019-03-09 01:37发布

I am trying to understand why do we really need lambda or proc in ruby (or any other language for that matter)?

#method
def add a,b
  c = a+b
end

#using proc
def add_proc a,b
  f = Proc.new {|x,y| x + y }
  f.call a,b
end

#using lambda function
def add_lambda a,b
  f = lambda {|x,y| x + y}
  f.call a,b
end

puts add 1,1
puts add_proc 1,2
puts add_lambda 1,3

I can do a simple addition using: 1. normal function def, 2. using proc and 3. using lambda.

But why and where use lambda in the real world? Any examples where functions cannot be used and lambda should be used.

7条回答
闹够了就滚
2楼-- · 2019-03-09 02:06

It comes down to style. Lambdas are a a declarative style, methods are an imperative style. Consider this:

Lambda, blocks, procs, are all different types of closure. Now the question is, when and why to use an anonymous closure. I can answer that - at least in ruby!

Closures contain the lexical context of where they were called from. If you call a method from within a method, you do not get the context of where the method was called. This is due to the way the object chain is stored in the AST.

A Closure (lambda) on the other hand, can be passed WITH lexical context through a method, allowing for lazy evaluation.

Also lambdas naturally lend themselves to recursion and enumeration.

查看更多
登录 后发表回答