What is a lambda and what is an example implementation?

后端 未结 6 881
轮回少年
轮回少年 2020-12-30 15:43

I am fairly new to programming and while doing a lot of reading this concept of a lambda keeps coming up but I\'m having a hard time putting my finger on what it actually is

6条回答
  •  难免孤独
    2020-12-30 16:32

    Lambda is a means of creating an anonymous function or closure. In imperative languages (and functional ones) it is equivalent to allowing nested functions where the inner function has access to local variable and parameters of the enclosing function. It is found in functional languages under the keywords lambda, fun, fn or even \; in Smalltalk it is called a block. It is also found in most scripting languages, e.g., Perl, Python, Lua, etc.

    About the only languages without lambda are

    • Languages without nested functions, like Standard C or Icon

    • Languages with second-class nested functions---a function may not be returned from a function, stored in a global variable, or stored in a heap-allocated data structure. This language family includes Pascal and its descendants in the Modula, Ada, and CLU families.

    Lambda has important implications for programmers and compiler writers: it is no longer possible to store all local variables on a stack. Instead some variables may be captured and stored in a heap-allocated closure. Be aware that when you write lambda you are writing an allocation.

    Example: one of the simplest functions is composition (Haskell syntax):

    compose f g = \x -> f (g x)
    

    This says that compose takes two functions f and g as arguments, and it returns an anonymous function which takes its argument x and then applies g and then f to x. An application of compose creates a closure allocated on the heap which stores the value of f and g as well as a pointer to code for the body of the lambda. In languages where lambda is common, such as Haskell, ML, Caml, and Scheme, a great deal of effort has been expended making allocation blindingly fast. Some scripting languages, such as Lua, have unusual implementations which make the non-lambda case the same as in an imperative language, while also making lambda reasonably fast. Lambda is also fast in Smalltalk, which was also designed to allocated lots of objects on the heap. In languages where lambda was retrofitted, like Perl or Java (inner classes are related to lambda), the expense can be relatively much higher.

    In general, if a language was designed with lambdas in mind, you can use them as much as you like. Especially in ML, Caml, Scheme, Haskell, even anonymous functions are dirt cheap---use lots of them!

提交回复
热议问题