What is a lambda (function)?

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

    A Lambda Function, or a Small Anonymous Function, is a self-contained block of functionality that can be passed around and used in your code. Lambda has different names in different programming languages – Lambda in Python and Kotlin, Closure in Swift, or Block in C and Objective-C. Although lambda's meaning is quite similar for these languages it has slight distinctions sometimes.

    Let's see how Lambda (Closure) works in Swift 4.2 with sorted() method – from normal function till the shortest expression:

    let coffee: [String] = ["Cappuccino", "Espresso", "Latte", "Ristretto"]
    

    1. Normal Function

    func backward(_ n1: String, _ n2: String) -> Bool {
        return n1 > n2
    }
    var reverseOrder = coffee.sorted(by: backward)
    
    
    // RESULT: ["Ristretto", "Latte", "Espresso", "Cappuccino"]
    

    2. Closure Expression

    reverseOrder = coffee.sorted(by: { (n1: String, n2: String) -> Bool in
        return n1 > n2
    })
    

    3. Inline Closure Expression

    reverseOrder = coffee.sorted(by: { (n1: String, n2: String) -> Bool in return n1 > n2 } )
    

    4. Inferring Type From Context

    reverseOrder = coffee.sorted(by: { n1, n2 in return n1 > n2 } )
    

    5. Implicit Returns from Single-Expression Closures

    reverseOrder = coffee.sorted(by: { n1, n2 in n1 > n2 } )
    

    6. Shorthand Argument Names

    reverseOrder = coffee.sorted(by: { $0 > $1 } )
    
    // $0 and $1 are closure’s first and second String arguments.
    

    7. Operator Methods

    reverseOrder = coffee.sorted(by: >)
    
    // RESULT: ["Ristretto", "Latte", "Espresso", "Cappuccino"]
    

    Hope this helps.

提交回复
热议问题