Partially applied functions in F#
January 28, 2017 Leave a comment
F# has a number of interesting features related to functions. After all it’s a functional language, right? One of those features is called partial application of a function. Partial application means that in F# we can supply the arguments to function at various stages. We don’t have to provide all input parameters at once.
This feature can be explained through function types in F#.
Consider the following function that adds three numbers:
let addThreeNumbers x y z = x + y + z
Its function type is expressed as follows:
x:int -> y:int -> z:int -> int
…, i.e. an integer to an integer to an integer to an integer. We can group these elements in various ways including the following:
x:int -> (y:int -> z:int) -> int
…which will be an integer to another function with an input of int and an output of an int. This output is then applied to the last integer.
We can declared a partially applied function like we declare a normal function. We simply supply only part of the required parameters. E.g. we can have another function where addThreeNumbers is always called with 3 and 5 as the first two parameters, i.e. x and y:
let partiallyAppliedAddThreeNumbers = addThreeNumbers 3 5
This will create a new function partiallyAppliedAddThreeNumbers with 1 input parameter, i.e. the one missing from addThreeNumbers which is the parameter ‘z’. We can call partiallyAppliedAddThreeNumbers as follows:
…which will give 3 + 5 + 7 = 15.
Partial function application is similar to method overloading and optional parameters in C#.
View all F# related articles here.