Skip to content

Partial application

impworks edited this page Oct 11, 2014 · 3 revisions

Partial application is a powerful feature that allows creating new functions by applying a subset of arguments to existing ones. Unspecified arguments are substituted by underscore character:

let sum:int (x:int y:int z:int) -> x + y + z
let add2 = sum 2 _ _
let alsoAdd2 = sum 1 _ 1

Basically, partial application is a lambda expression in disguise. The code above is equivalent to the following snippet:

let sum:int (x:int y:int z:int) -> x + y + z
let add2 = (p1:int p2:int) -> sum 2 p1 p2
let alsoAdd2 = (p1:int) -> sum 1 p1 1

Any callable expression can be partially applied, including constructors:

let tupler = new Tuple<int,int> _ _
let value = tupler 2 1

If the callable expression is a method with overloads, the specified list of arguments must unambiguously define one exact overload. Otherwise, an error is thrown:

fun plus:int (x:int y:int) -> x + y
fun plus:string (x:int y:string) -> x.ToString() + y

var addInt = plus _ 2 // OK
var wtf = plus 2 _    // Both functions match, would not compile