Partially applying functions in F#

A cool feature of a functional language like F# is the ability to partially apply a function. Take this add function:

let add x y = x + y

By partially applying this function we can create new functions like this:

let plus1 = add 1
let plus5 = add 5

The functions we have created plus1 and plus5 both have the signature int -> int. We have partially applied add to a single parameter leaving us with a function that takes one more int and returns us an int. This is a really neat idea.

Building on this if we want to do the same thing with subtract we find that it does not quite work:

let subtract x y = x - y
let minus1 = subtract 1
printfn "%i" (minus1 7)

The code above prints -6 when we wanted our minus1 function to subtract 1 from the argument given. This is because unlike with add it matters the order that you give the arguments to subtract. We have another cool trick up our sleeves to solve this:

let subtract x y = x - y
let swap f x y = f y x
let minus = swap subtract
let minus1 = minus 1
printfn "%i" (minus1 7)

The minus1 function above now does what we would expect. To make this work we defined a swap function that swaps the order of the arguments. We can then pass our subtract function to our swap function to produce a new subtract function that takes its arguments in the opposite order. We can now partially apply the new function minus with 1 to give us a new function minus1 that works how we would expect. Having functions as a first class citizen really does lead to some neat code.

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s