Where and when to use Lambda?

后端 未结 7 2015
执笔经年
执笔经年 2021-01-31 16:47

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
de         


        
相关标签:
7条回答
  • 2021-01-31 17:46

    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.

    0 讨论(0)
提交回复
热议问题