# Lambda expressions in F#

May 27, 2017 2 Comments

Lambda expressions in F# are inline anonymous functions, i.e. functions without a name. They are typically short and concise functions that are not meant to be reused.

Here’s a normal F# function that adds three numbers:

let addThreeNumbers x y z = x + y + z

This is a conventional named function that can be invoked from other parts of the application. We can convert it to a lambda function using the “fun” keyword. However, it must be invoked in place.

Here’s how to rewrite the above function into a lambda function:

let someOfThree = (fun x y z -> x + y + z) 10 20 30

The fun keyword is followed by the input parameters x, y and z. Then comes the arrow delimiter -> followed by the short function body which is only a return statement. We finally have the arguments into the lambda function. This is obviously no different from a normal function call:

let someOfThreeAlt = addThreeNumbers 10 20 30

The difference is only that “addThreeNumbers” was transformed into an anonymous function. Otherwise anonymous functions behave exactly as normal functions with input parameters, a method body and a return statement.

We can also declare the input types:

let someOfThree = (fun (x:int) (y:int) (z:int) -> x + y + z) 10 20 30

Here’s another example to find the absolute value of the difference between two numbers:

let absoluteValue = (fun (x:int) (y:int) -> x - y |> abs) 20 10

View all F# related articles here.

Pingback: F# Weekly #22, 2017 with 2017 F# survey results – Sergey Tihon's Blog

Pingback: The week in .NET – Open XML SDK, Adventure Time – Site Design