Anonymous functions in F#
January 22, 2017 Leave a comment
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:
[<EntryPoint>] 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.