Anonymous functions in F#

Anonymous functions in F# are used to build functions that are meant to be used within a statement. They have no names so other parts of the application can’t call them.

The following named function…:

let increment x = x + 1

…has the following anonymous counterpart:

fun x -> x + 1

The input parameter x is followed by the -> operator as opposed to the ‘=’ function assignment operator. Here’s how this declaration can be used within another statement:

printfn "%i" ((fun x -> x + 1) 5)

The anonymous function is followed by the input parameter 5 which will take the place of ‘x’.

We can declare the input parameter type:

printfn "%i" ((fun (x:int) -> x + 1) 5)

We can have multiple input parameters:

printfn "%i" ((fun (x:int) (y:int) -> x + y) 5 9)

5 will be assigned to x and 9 will be assigned to y.

We can have multiple statements in the function body. Take care of the indentation:

let main argv =  
    printfn "%i" ((fun (x:int) (y:int) ->
        printfn "%s" "Calling an anonymous function!!!"
        printfn "You have called this anonymous function with %i and %i" x y
        x + y) 5 9)

This prints the following message:

Calling an anonymous function!!!
You have called this anonymous function with 5 and 9

View all F# related articles here.


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

Leave a Reply

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

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

Twitter picture

You are commenting using your Twitter 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


Once Upon a Camayoc

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

%d bloggers like this: