What is a lambda (function)?

后端 未结 23 2198
太阳男子
太阳男子 2020-11-22 04:47

For a person without a comp-sci background, what is a lambda in the world of Computer Science?

相关标签:
23条回答
  • 2020-11-22 05:18

    An example of a lambda in Ruby is as follows:

    hello = lambda do
        puts('Hello')
        puts('I am inside a proc')
    end
    
    hello.call
    

    Will genereate the following output:

    Hello
    I am inside a proc
    
    0 讨论(0)
  • 2020-11-22 05:19

    For a person without a comp-sci background, what is a lambda in the world of Computer Science?

    I will illustrate it intuitively step by step in simple and readable python codes.

    In short, a lambda is just an anonymous and inline function.

    Let's start from assignment to understand lambdas as a freshman with background of basic arithmetic.

    The blueprint of assignment is 'the name = value', see:

    In [1]: x = 1
       ...: y = 'value'
    In [2]: x
    Out[2]: 1
    In [3]: y
    Out[3]: 'value'
    

    'x', 'y' are names and 1, 'value' are values. Try a function in mathematics

    In [4]: m = n**2 + 2*n + 1
    NameError: name 'n' is not defined
    

    Error reports,
    you cannot write a mathematic directly as code,'n' should be defined or be assigned to a value.

    In [8]: n = 3.14
    In [9]: m = n**2 + 2*n + 1
    In [10]: m
    Out[10]: 17.1396
    

    It works now,what if you insist on combining the two seperarte lines to one. There comes lambda

    In [13]: j = lambda i: i**2 + 2*i + 1
    In [14]: j
    Out[14]: <function __main__.<lambda>>
    

    No errors reported.

    This is a glance at lambda, it enables you to write a function in a single line as you do in mathematic into the computer directly.

    We will see it later.

    Let's continue on digging deeper on 'assignment'.

    As illustrated above, the equals symbol = works for simple data(1 and 'value') type and simple expression(n**2 + 2*n + 1).

    Try this:

    In [15]: x = print('This is a x')
    This is a x
    In [16]: x
    In [17]: x = input('Enter a x: ')
    Enter a x: x
    

    It works for simple statements,there's 11 types of them in python 7. Simple statements — Python 3.6.3 documentation

    How about compound statement,

    In [18]: m = n**2 + 2*n + 1 if n > 0
    SyntaxError: invalid syntax
    #or
    In [19]: m = n**2 + 2*n + 1, if n > 0
    SyntaxError: invalid syntax
    

    There comes def enable it working

    In [23]: def m(n):
        ...:     if n > 0:
        ...:         return n**2 + 2*n + 1
        ...:
    In [24]: m(2)
    Out[24]: 9
    

    Tada, analyse it, 'm' is name, 'n**2 + 2*n + 1' is value.: is a variant of '='.
    Find it, if just for understanding, everything starts from assignment and everything is assignment.

    Now return to lambda, we have a function named 'm'

    Try:

    In [28]: m = m(3)
    In [29]: m
    Out[29]: 16
    

    There are two names of 'm' here, function m already has a name, duplicated.

    It's formatting like:

    In [27]: m = def m(n):
        ...:         if n > 0:
        ...:             return n**2 + 2*n + 1
        SyntaxError: invalid syntax
    

    It's not a smart strategy, so error reports

    We have to delete one of them,set a function without a name.

    m = lambda n:n**2 + 2*n + 1
    

    It's called 'anonymous function'

    In conclusion,

    1. lambda in an inline function which enable you to write a function in one straight line as does in mathematics
    2. lambda is anonymous

    Hope, this helps.

    0 讨论(0)
  • 2020-11-22 05:20

    Lambda explained for everyone:

    Lambda is an annonymous function. This means lambda is a function objekt in Python that doesnt require a reference before. Let's concider this bit of code here:

    def name_of_func():
        #command/instruction
        print('hello')
    
    print(type(name_of_func))   #the name of the function is a reference
                                #the reference contains a function Objekt with command/instruction
    

    To proof my proposition I print out the type of name_of_func which returns us:

    <class 'function'>
    

    A function must have a interface, but a interface dosent needs to contain something. What does this mean? Let's look a little bit closer to our function and we may notice that out of the name of the functions there are some more details we need to explain to understand what a function is.

    A regular function will be defined with the syntax "def", then we type in the name and settle the interface with "()" and ending our definition by the syntax ":". Now we enter the functions body with our instructions/commands.

    So let's consider this bit of code here:

    def print_my_argument(x):
        print(x)
    
    
    print_my_argument('Hello')
    

    In this case we run our function, named "print_my_argument" and passing a parameter/argument through the interface. The Output will be:

    Hello
    

    So now that we know what a function is and how the architecture works for a function, we can take a look to an annonymous function. Let's consicder this bit of code here:

    def name_of_func():
        print('Hello')
    
    
    
    lambda: print('Hello')
    

    these function objekts are pretty much the same except of the fact that the upper, regular function have a name and the other function is an annonymous one. Let's take a closer look on our annonymous function, to understand how to use it.

    So let's concider this bit of code here:

    def delete_last_char(arg1=None):
        print(arg1[:-1])
    
    string = 'Hello World'
    delete_last_char(string)
    
    f = lambda arg1=None: print(arg1[:-1])
    f(string)
    

    So what we have done in the above code is to write once againg, a regular function and an anonymous function. Our anonymous function we had assignd to a var, which is pretty much the same as to give this function a name. Anyway, the output will be:

    Hello Worl
    Hello Worl
    

    To fully proof that lambda is a function object and doesnt just mimik a function we run this bit of code here:

    string = 'Hello World'
    f = lambda arg1=string: print(arg1[:-1])
    f()
    print(type(f))
    

    and the Output will be:

    Hello Worl
    <class 'function'>
    

    Last but not least you should know that every function in python needs to return something. If nothing is defined in the body of the function, None will be returned by default. look at this bit of code here:

    def delete_last_char(arg1):
        print(arg1[:-1])
    
    string = 'Hello World'
    x = delete_last_char(string)
    
    f = lambda arg1=string: print(arg1[:-1])
    x2 = f()
    
    print(x)
    print(x2)
    

    Output will be:

    Hello Worl
    Hello Worl
    None
    None
    
    0 讨论(0)
  • 2020-11-22 05:24

    The lambda calculus is a consistent mathematical theory of substitution. In school mathematics one sees for example x+y=5 paired with x−y=1. Along with ways to manipulate individual equations it's also possible to put the information from these two together, provided cross-equation substitutions are done logically. Lambda calculus codifies the correct way to do these substitutions.

    Given that y = x−1 is a valid rearrangement of the second equation, this: λ y = x−1 means a function substituting the symbols x−1 for the symbol y. Now imagine applying λ y to each term in the first equation. If a term is y then perform the substitution; otherwise do nothing. If you do this out on paper you'll see how applying that λ y will make the first equation solvable.

    That's an answer without any computer science or programming.

    The simplest programming example I can think of comes from http://en.wikipedia.org/wiki/Joy_(programming_language)#How_it_works:

    here is how the square function might be defined in an imperative programming language (C):

    int square(int x)
    {
        return x * x;
    }
    

    The variable x is a formal parameter which is replaced by the actual value to be squared when the function is called. In a functional language (Scheme) the same function would be defined:

    (define square
      (lambda (x) 
        (* x x)))
    

    This is different in many ways, but it still uses the formal parameter x in the same way.


    Added: http://imgur.com/a/XBHub

    0 讨论(0)
  • 2020-11-22 05:24

    I like the explanation of Lambdas in this article: The Evolution Of LINQ And Its Impact On The Design Of C#. It made a lot of sense to me as it shows a real world for Lambdas and builds it out as a practical example.

    Their quick explanation: Lambdas are a way to treat code (functions) as data.

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