Lambda expressions in F#

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.

Advertisement

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

2 Responses to Lambda expressions in F#

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

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: