What is a lambda (function)?

后端 未结 23 2289
太阳男子
太阳男子 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:14

    The name "lambda" is just a historical artifact. All we're talking about is an expression whose value is a function.

    A simple example (using Scala for the next line) is:

    args.foreach(arg => println(arg))
    

    where the argument to the foreach method is an expression for an anonymous function. The above line is more or less the same as writing something like this (not quite real code, but you'll get the idea):

    void printThat(Object that) {
      println(that)
    }
    ...
    args.foreach(printThat)
    

    except that you don't need to bother with:

    1. Declaring the function somewhere else (and having to look for it when you revisit the code later).
    2. Naming something that you're only using once.

    Once you're used to function values, having to do without them seems as silly as being required to name every expression, such as:

    int tempVar = 2 * a + b
    ...
    println(tempVar)
    

    instead of just writing the expression where you need it:

    println(2 * a + b)
    

    The exact notation varies from language to language; Greek isn't always required! ;-)

提交回复
热议问题