Skip to content

Function composition

Andrey Kurosh edited this page Jun 20, 2017 · 5 revisions

Several functions can be piped together, so that the return of one function is the argument to the next one. The :> operator is used to compose functions.

Consider the following code sample:

let inc = x:int -> x + 1
let mult = x:int -> x * 2
let c1 = inc :> mult
let c2 = mult :> inc

print (c1 2) // 6
print (c2 2) // 5

Static methods are also supported:

let invConcat = (a:string b:string) -> b + a
let invParse = incConcat :> int::Parse

invParse "37" "13" // 1337

Partial application

The first function in line may have as many arguments as it is desired. The latter, however, may only have one argument. As the type of the argument can easily be inferred, it may be omitted at lambda definition:

let sum = (a:int b:int c:int) -> a + b + c
let composed = sum :> (x -> x.ToString()) // (int, int, int -> string)

Partial application may come in handy when you need to chain in a function that accepts more than 1 argument:

fun add:int (x:int y:int) -> x + y
let addTwo = int::TryParse<string> :> add 2 _
addTwo "40" // 42

Read more

Clone this wiki locally