Home

F# Topics on Functions: Lambda Expressions

   

Introduction

A lambda expression is a function that is not standing on its own and doesn't have a name. For this reason, a lambda expression is also referred to as an anonymous function.

We saw that, before calling a function that takes a function value as argument, we needed an external function that would actually do what the function value is meant for. A lambda expression can take care of that. Instead of defining an external function, create a lambda expression where that external function would be called.

To create a lambda expression, use the fun or the function keyword in place of the function name. After the keyword, you can specify 0 or more parameters. Instead of the = operator that introduces the body of a function, use the -> operator. This is followed by the body of the function where you define what the function does. The formula to follow is:

fun parameter(s) -> body

A Lambda Expression With No Parameter

You can create a lambda expression that takes no parameter. In this case, you can use either a wildcard underscore or empty parentheses in place of the parameter. Here are examples:

let show1() = fun _ -> printfn "Welcome to this wonderful world"
let show2() = fun () -> printfn "Welcome to this wonderful world"
let show3() = function () -> printfn "Welcome to this wonderful world"

After doing this, if you simply call the function, you would not get anything. One approach is to first declare a variable and assign the function call to it. Here is an example:

let caller = show()

You can then treat that variable as if it were a function and call it as such. Here is an example:

let show() = function () -> printfn "Welcome to this wonderful world"


let caller = show()


caller()

Alternatively, you don't have to first create a function. You can assign the lambda expression directly to the variable. Here is an example:

let caller = fun _ -> printfn "Welcome to this wonderful world"

caller()

A Lambda Expression With One Parameter

A lambda expression can take one parameter. To specify it, after the fun or the function keyword, type the name of the parameter followed by ->. After the -> operator, ignore or use parameter. Here is an example:

fun x -> x / 100.00

To use the value of the lambda expression, you have many options. You can assign it to a variable. In this case, write the whole function in parentheses. After the parentheses, specify the value that the function is supposed to process. Here is an example:

open System
open System.Windows.Forms

let businessMathematics = new Form()
businessMathematics.Text   <- "Business Mathematics"
businessMathematics.Width  <- 210
businessMathematics.Height <- 165

let lblValue = new Label()
lblValue.Left  <- 18
lblValue.Top   <- 18
lblValue.Width <- 65
lblValue.Text  <- "Value:"
businessMathematics.Controls.Add lblValue

let txtValue = new TextBox()
txtValue.Left  <- 90
txtValue.Top   <- 16
txtValue.Width <- 45
txtValue.Text  <- "0.00"
businessMathematics.Controls.Add txtValue

let lblPercent = new Label()
lblPercent.Left  <- 136
lblPercent.Top   <- 19
lblPercent.Width <- 20
lblPercent.Text  <- "%"
businessMathematics.Controls.Add lblPercent

let btnConvert = new Button()
btnConvert.Left  <- 90
btnConvert.Top   <- 44
btnConvert.Text  <- "Convert"

let lblConverted = new Label()
lblConverted.Left  <- 18
lblConverted.Top   <- 78
lblConverted.Width <- 70
lblConverted.Text  <- "Converted:"
businessMathematics.Controls.Add lblConverted

let txtConverted = new TextBox()
txtConverted.Left  <- 90
txtConverted.Top   <- 74
txtConverted.Width <- 75
txtConverted.Text  <- "0.00"
businessMathematics.Controls.Add txtConverted

let btnConvertClick e =
    let value = float txtValue.Text

    let result = (fun x -> x / 100.00) value
    let strResult = sprintf "%0.04f" result

    txtConverted.Text <- strResult

btnConvert.Click.Add btnConvertClick
businessMathematics.Controls.Add btnConvert

let btnClose = new Button()
btnClose.Left  <- 90
btnClose.Top   <- 104
btnClose.Width <-  75
btnClose.Text  <- "Close"
let btnCloseClick e = businessMathematics.Close()
btnClose.Click.Add btnCloseClick
businessMathematics.Controls.Add btnClose

Application.Run businessMathematics

Here is an example of running the program:

Lambda Expressions

Lambda Expressions

The most common reason to use a lambda expression is to define a function in a local area where only a single call of the function is needed. This means that one of the reasons to use a lambda expression is to create a function that is needed only once. Other than that, a lambda expression can be as complex as you want, not just a simple one-line statement. It can include its own local variables and it can have internal expressions such as conditional statements. Here is an example:

Author Note

Piecework is a system by which an employee (or contractor) is paid based on a number of units or items. Examples are the number of pineapples an employee has collected in a farm, the number chips an employee has assembled, the number shirts sewn, etc.

Companies use two primary ways to pay their piecework employees. In one case, an employee can be paid straight on the number of units. In another case, there is a rate on the first number of items such as 100, then there is a second rate for the second fraction such as units between 101 and 200, and finally there is a last rate such as for the number of units over 200.

In the following example, a microchip company is paying employees who assemble the chips:

Units Price Each
Between 1 and 100 units 2.25
From 101 to 250 2.45
More Than 250 2.68
open System
open System.Windows.Forms

let microchipCompany = new Form()
microchipCompany.Text   <- "Microchip Company"
microchipCompany.Width  <- 210
microchipCompany.Height <- 165

let lblUnits = new Label()
lblUnits.Left  <- 18
lblUnits.Top   <- 18
lblUnits.Width <- 90
lblUnits.Text  <- "Number of Units:"
microchipCompany.Controls.Add lblUnits

let txtUnits = new TextBox()
txtUnits.Left  <- 110
txtUnits.Top   <- 16
txtUnits.Width <- 75
txtUnits.Text  <- "0"
microchipCompany.Controls.Add txtUnits

let btnCalculate = new Button()
btnCalculate.Left  <- 110
btnCalculate.Top   <-  44
btnCalculate.Text  <- "Calculate"

let lblGrossSalary = new Label()
lblGrossSalary.Left  <- 18
lblGrossSalary.Top   <- 78
lblGrossSalary.Width <- 90
lblGrossSalary.Text  <- "Gross Salary:"
microchipCompany.Controls.Add lblGrossSalary

let txtGrossSalary = new TextBox()
txtGrossSalary.Left  <- 110
txtGrossSalary.Top   <- 74
txtGrossSalary.Width <- 75
txtGrossSalary.Text  <- "0.00"
microchipCompany.Controls.Add txtGrossSalary

let btnCalculateClick e =
    let items = float txtUnits.Text

    let grossSalary = (fun units ->
        if units <= 100.00 then units * 2.25
        elif units <= 250.00 then
            let first100 = 100.00 * 2.45
            let others = (units - 100.00) * 2.25
            first100 + others
        else
            let first100 = 100.00 * 2.25
            let between100And250 = 150.00 * 2.45
            let others = (units - 250.00) * 2.68
            first100 + between100And250 + others) items
        
    txtGrossSalary.Text <- sprintf "%0.02f" grossSalary

btnCalculate.Click.Add btnCalculateClick
microchipCompany.Controls.Add btnCalculate

let btnClose = new Button()
btnClose.Left  <- 110
btnClose.Top   <- 104
btnClose.Width <-  75
btnClose.Text  <- "Close"
let btnCloseClick e = microchipCompany.Close()
btnClose.Click.Add btnCloseClick
microchipCompany.Controls.Add btnClose

Application.Run microchipCompany

Here is an example of running the program:

Introduction to Lambda Expressions

Introduction to Lambda Expressions

A Lambda Expression With Many Parameters

Instead of one, a lambda expression can take many arguments. In this case, you must use the fun. The function keyword is not appropriate. Here is an example of a lambda expression that takes two parameters:

Author Note

Some companies pay their employees (or contractors) on a commission basis. There are various options. For example, a company may apply a base salary plus a percentage based on a certain number of products (or items) sold (or produced).

In the following example, a company pays a commission rate of 6% to its employees based on their weekly sales.

open System
open System.Windows.Forms

let productsCompany = new Form()
productsCompany.Text   <- "Products Company"
productsCompany.Width  <- 300
productsCompany.Height <- 140

let lblWeeklySales = new Label()
lblWeeklySales.Left  <-  18
lblWeeklySales.Top   <-  18
lblWeeklySales.Width <- 112
lblWeeklySales.Text  <- "Weekly Sales:"
productsCompany.Controls.Add lblWeeklySales

let txtWeeklySales = new TextBox()
txtWeeklySales.Left  <- 130
txtWeeklySales.Top   <- 16
txtWeeklySales.Width <- 64
txtWeeklySales.Text  <- "0.00"
productsCompany.Controls.Add txtWeeklySales

let lblCommissionRate = new Label()
lblCommissionRate.Left  <- 18
lblCommissionRate.Top   <- 46
lblCommissionRate.Width <- 112
lblCommissionRate.Text  <- "Commission Rate:"
productsCompany.Controls.Add lblCommissionRate

let txtCommissionRate = new TextBox()
txtCommissionRate.Left  <- 130
txtCommissionRate.Top   <-  44
txtCommissionRate.Width <-  44
txtCommissionRate.Text  <- "0.00"
productsCompany.Controls.Add txtCommissionRate

let lblPercent = new Label()
lblPercent.Left  <- 175
lblPercent.Top   <- 48
lblPercent.Width <- 20
lblPercent.Text  <- "%"
productsCompany.Controls.Add lblPercent

let btnCalculate = new Button()
btnCalculate.Left <- 202
btnCalculate.Top  <- 43
btnCalculate.Text <- "Calculate"

let lblCommissionAmount = new Label()
lblCommissionAmount.Left  <- 18
lblCommissionAmount.Top   <- 76
lblCommissionAmount.Width <- 112
lblCommissionAmount.Text  <- "Commission Amount:"
productsCompany.Controls.Add lblCommissionAmount

let txtCommissionAmount = new TextBox()
txtCommissionAmount.Left  <- 130
txtCommissionAmount.Top   <-  74
txtCommissionAmount.Width <-  64
txtCommissionAmount.Text  <- "0.00"
productsCompany.Controls.Add txtCommissionAmount

let btnClose = new Button()
btnClose.Left <- 202
btnClose.Top  <-  73
btnClose.Text <- "Close"

let btnCalculateClick(e) =
    let weeklySales = float txtWeeklySales.Text
    let commissionRate = float txtCommissionRate.Text
    
    let commissionAmount = (fun x y -> x * y / 100.00) weeklySales commissionRate
    
    let strCommissionAmount = sprintf "%0.02f" commissionAmount
    txtCommissionAmount.Text <- strCommissionAmount

btnCalculate.Click.Add btnCalculateClick
productsCompany.Controls.Add btnCalculate

let btnCloseClick e = productsCompany.Close()
btnClose.Click.Add btnCloseClick
productsCompany.Controls.Add btnClose

do Application.Run productsCompany

Here is an example of running the program:

Lambda Expressions

Lambda Expressions

     
 

Lambda Expressions and Functions

A function can take a lambda expression as arguments. On one hand,  you can create an expression that uses the same lambda expression more than once. On the other hand, you can create a statement that includes different lambda expressions. Here is an example:

open System
open System.Windows.Forms

let calculateInterest (statement : float -> float -> float -> float) (totalize : float -> float -> float) printcipal rate periods =
    let totalInterest = statement printcipal rate periods
    totalize printcipal totalInterest

// Compound Interest
let simpleInterest : Form = new Form()
simpleInterest.Text <- "Compound Interest"
simpleInterest.Width <- 290
simpleInterest.Height <- 180

// Label: Principal
let lblPrincipal : Label = new Label()
lblPrincipal.Text   <- "Principal:"
lblPrincipal.Left   <- 19
lblPrincipal.Top    <- 23
lblPrincipal.Width  <- 72
simpleInterest.Controls.Add lblPrincipal

// Text Box: Principal
let txtPrincipal : TextBox = new TextBox()
txtPrincipal.Text  <- "0.00"
txtPrincipal.Left  <- 95
txtPrincipal.Top   <- 20
txtPrincipal.Width <- 64
simpleInterest.Controls.Add txtPrincipal

// Label: Interest Rate
let lblInterestRate : Label = new Label()
lblInterestRate.Text  <- "Interest Rate: 10.25%"

lblInterestRate.Left  <- 18
lblInterestRate.Top   <- 49
lblInterestRate.Width <- 180
simpleInterest.Controls.Add lblInterestRate

// Label: Periods
let lblPeriods : Label = new Label()
lblPeriods.Text  <- "Periods:"
lblPeriods.Left  <- 18
lblPeriods.Top   <- 75
lblPeriods.Width <- 75
simpleInterest.Controls.Add lblPeriods

// Text Box: Periods
let txtPeriods : TextBox = new TextBox()
txtPeriods.Text  <- "0"
txtPeriods.Left  <- 95
txtPeriods.Top   <- 72
txtPeriods.Width <- 45
simpleInterest.Controls.Add txtPeriods

// Label: Years
let lblYears : Label = new Label()
lblYears.Text  <- "Years"
lblYears.Left  <- 146
lblYears.Top   <- 75
lblYears.Width <- 40
simpleInterest.Controls.Add lblYears

// Button: Calculate
let btnCalculate : Button = new Button()
btnCalculate.Text <- "Calculate"
btnCalculate.Left <- 186
btnCalculate.Top <- 72
simpleInterest.Controls.Add btnCalculate

// Label: Future Value
let lblFutureValue : Label = new Label()
lblFutureValue.Left  <- 19
lblFutureValue.Top   <- 112
lblFutureValue.Width <- 75
lblFutureValue.Text  <- "Future Value:"
simpleInterest.Controls.Add lblFutureValue

// Text Box: Future Value
let txtFutureValue : TextBox = new TextBox()
txtFutureValue.Text  <- "0.00"
txtFutureValue.Left  <- 95
txtFutureValue.Top   <- 110
txtFutureValue.Width <- 64
simpleInterest.Controls.Add txtFutureValue

let btnCalculateClick _ =
    let principal = float txtPrincipal.Text
    let interestRate = 10.25
    let periods = float txtPeriods.Text

    let futureValue = calculateInterest (fun a b c -> a * b * c) (fun a b -> a + b) principal (interestRate / 100.00) periods

    let strFutureValue = sprintf "%0.02f" futureValue
    txtFutureValue.Text <- strFutureValue

btnCalculate.Click.Add btnCalculateClick

// Button: Close
let btnClose : Button = new Button()
btnClose.Text <- "Close"
btnClose.Left <- 186
btnClose.Top <- 108
let btnCloseClick (e : EventArgs) =
    simpleInterest. Close()
btnClose.Click.Add btnCloseClick
simpleInterest.Controls.Add btnClose   

do Application.Run simpleInterest

You can also use a lambda expression that itself takes arguments. Consider the following expression:

open System
open System.Windows.Forms

let stockTrade = new Form()
stockTrade.Text   <- "Stock Trade"
stockTrade.Width  <- 245
stockTrade.Height <- 250

let lblShares = new Label()
lblShares.Left  <- 18
lblShares.Top   <- 19
lblShares.Width <- 100
lblShares.Text  <- "Number of Shares:"
stockTrade.Controls.Add lblShares

let txtShares = new TextBox()
txtShares.Left    <- 130
txtShares.Top     <- 16
txtShares.Width <- 75
txtShares.Text    <- "0"
stockTrade.Controls.Add txtShares

let lblUnitPrice = new Label()
lblUnitPrice.Left  <- 18
lblUnitPrice.Top   <- 45
lblUnitPrice.Width <- 100
lblUnitPrice.Text  <- "Unit Price:"
stockTrade.Controls.Add lblUnitPrice

let txtUnitPrice = new TextBox()
txtUnitPrice.Left  <- 130
txtUnitPrice.Top   <-  44
txtUnitPrice.Width <-  50
txtUnitPrice.Text  <- "0.00"
stockTrade.Controls.Add txtUnitPrice

let lblPerShare = new Label()
lblPerShare.Left  <- 180
lblPerShare.Top   <- 46
lblPerShare.Width <- 44
lblPerShare.Text  <- "/Share:"
stockTrade.Controls.Add lblPerShare

let btnCalculate = new Button()
btnCalculate.Left <- 130
btnCalculate.Top  <-  74
btnCalculate.Text <- "Calculate"

let lblPrincipal = new Label()
lblPrincipal.Left  <-  18
lblPrincipal.Top   <- 114
lblPrincipal.Width <- 82
lblPrincipal.Text  <- "Principal:"
stockTrade.Controls.Add lblPrincipal

let txtPrincipal = new TextBox()
txtPrincipal.Left  <- 130
txtPrincipal.Top   <-  110
txtPrincipal.Width <-  75
txtPrincipal.Text  <- "0.00"
stockTrade.Controls.Add txtPrincipal

let lblCommissionAmount = new Label()
lblCommissionAmount.Left  <-  18
lblCommissionAmount.Top   <- 138
lblCommissionAmount.Width <- 112
lblCommissionAmount.Text  <- "Commission Amount:"
stockTrade.Controls.Add lblCommissionAmount

let txtCommissionAmount = new TextBox()
txtCommissionAmount.Left  <- 130
txtCommissionAmount.Top   <-  135
txtCommissionAmount.Width <-  75
txtCommissionAmount.Text  <- "0.00"
stockTrade.Controls.Add txtCommissionAmount

let lblTotalInvestment = new Label()
lblTotalInvestment.Left  <-  18
lblTotalInvestment.Top   <- 164
lblTotalInvestment.Width <- 100
lblTotalInvestment.Text  <- "Total Investment:"
stockTrade.Controls.Add lblTotalInvestment

let txtTotalInvestment = new TextBox()
txtTotalInvestment.Left  <- 130
txtTotalInvestment.Top   <-  161
txtTotalInvestment.Width <-  75
txtTotalInvestment.Text  <- "0.00"
stockTrade.Controls.Add txtTotalInvestment

let btnClose = new Button()
btnClose.Left <- 130
btnClose.Top  <- 192
btnClose.Text <- "Close"

let btnCalculateClick(e) =
    let numberOfShares = float txtShares.Text
    let unitPrice   = float txtUnitPrice.Text

    let principal        = (fun x y -> x * y) numberOfShares unitPrice

    let commissionBase = if   principal <   2499.00 then  26.25
                         elif principal <   5999.00 then  45.00
                         elif principal <  19999.00 then  60.00
                         elif principal <  49999.00 then  75.00
                         elif principal < 499999.00 then 131.25
                         else                            206.25

    let commissionRate = if   principal <   2499.00 then 1.40
                         elif principal <   5999.00 then 0.54   / 100.00
                         elif principal <  19999.00 then 0.28   / 100.00
                         elif principal <  49999.00 then 0.1875 / 100.00
                         elif principal < 499999.00 then 0.09   / 100.00
                         else                            0.0075 / 100.00
                                    
    let commissionAmount = (fun x y z -> x + y * z) (if   principal <   2499.00 then  26.25
                                                     elif principal <   5999.00 then  45.00
                                                     elif principal <  19999.00 then  60.00
                                                     elif principal <  49999.00 then  75.00
                                                     elif principal < 499999.00 then 131.25
                                                     else 206.25)
                                                    (if   principal <   2499.00 then 1.40
                                                     elif principal <   5999.00 then 0.54   / 100.00
                                                     elif principal <  19999.00 then 0.28   / 100.00
                                                     elif principal <  49999.00 then 0.1875 / 100.00
                                                     elif principal < 499999.00 then 0.09   / 100.00
                                                     else 0.0075) ((fun x y -> x * y) numberOfShares unitPrice)

    let totalInvestment  = (fun x y -> x + y) ((fun a b -> a * b) numberOfShares unitPrice) ((fun a b c -> a + b  * c) commissionBase commissionRate ((fun u v -> u * v) numberOfShares unitPrice))

    let strPrincipal = sprintf "%0.02f" principal
    let strCommissionAmount = sprintf "%0.02f" commissionAmount
    let strTotalInvestment = sprintf "%0.02f" totalInvestment

    txtPrincipal.Text <- strPrincipal
    txtCommissionAmount.Text <- strCommissionAmount
    txtTotalInvestment.Text <- strTotalInvestment

btnCalculate.Click.Add(btnCalculateClick)
stockTrade.Controls.Add(btnCalculate)

let btnCloseClick e = stockTrade.Close()
btnClose.Click.Add btnCloseClick
stockTrade.Controls.Add btnClose

Application.Run stockTrade

Here is an example of running the program:

Lambda Expressions Lambda Expressions
   
   
 

Home Copyright © 2009-2015, FunctionX Home