Partially applied functions in F#

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:

partiallyAppliedAddThreeNumbers 7

…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.

Advertisement

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:

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: