Basics 07 - Lambda Expressions

Time to discuss lambda expressions.

Learning-FSharp/Ch07-LambdaExpressions/Program.fs

Check out all the comments that are placed in the source file.

What is a Lambda Expression?

Lamba expressions aka anonymous functions allow you to create nameless, in-place functions. The keyword used for lambda expressions is fun.

let someFunc param = ...

let someLambda = fun param -> ...

For all practical purposes, functions and lambda expressions are the same:

  1. Functions have parameters, so do the lambda expressions

  2. Functions return a value, so do the lambda expressions

  3. The only difference is the intent:

    1. A function once created is callable/injectable from anywhere; reusable

    2. A lambda expression, an in-place function, is injected and has no meaning/existence outside the scope

    3. Lambda expressions are typically used when a function creation is considered an overhead; typically for injecting one-off logic

    4. If the same concept/logic is injected at multiple places via lambda expressions, better create a function

Understanding Closures

The secret sauce used by the F# compiler to create the illusion of availability of non-local variables inside functions.

Let's take this example:

// Applies function f over parameter x
let apply1 f x = f x

[<EntryPoint>]
let main args =

    let val1 = 10

    apply1 (fun x -> x * val1) 10 |> printf "%d"

Pay attention to this: fun x -> x * val1.

The variable val1 is defined in the function main, and is neither local to the lambda expression nor is it supplied as a parameter. However, when apply1 is invoked, which in turn invokes the lambda expression, val1 is available. This is happening because the F# compiler is doing the heavy lifting here, knowsn as closure. val1 is available inside the lambda expression via a closure.

Lambda expression and partial application both are dependent on closures.

If you have reached so far, congratulations.

Keep reading!