Infix operators in F#
February 11, 2017 Leave a comment
F# makes the distinction between “prefix” and “infix” functions. The word prefix means that something comes before something else. Prepositions in many Indo-European languages, like “in”, “for” and “on” in English are examples of prefixes, they are placed in front of another word, most often a noun: in the house, at the station, for that purpose.
Prefix functions are how we most often define and call functions in F#. The function name comes first which is then followed by the function arguments.
Here’s a function that adds two numbers:
let addTwoNumbers x y = x + y
Unsurprisingly we call the above function as follows:
addTwoNumbers 3 5
The word “infix” on the other hand means something like “in between”. Infix functions in F#, also called infix operators, operate on two parameters and are placed in between those two parameters. All mathematical operators like +, -, / and * are examples of infix operators: 3 + 5, 10 / 2 etc. They are placed in between the two input parameters.
Infix operators can be applied in a prefix way. They must come before the parameters and must be put within parentheses:
let res = (/) 10 5
res will be 2 since that prefix expression is equal to 10 / 5 in an infix way.
We can also build our own infix operators. Their name can only consist of symbols and must be surrounded by parentheses when declared. Consider the following function that takes parameters and adds their squares:
let calc x y = x ** 2. + y ** 2.
Calling this function with 2 and 3…:
let res = calc 2. 3.
…gives 13. 2 ^ 2 = 4, 3 ^ 2 = 9, so 9 + 4 = 13.
We can define the calc function as an infix but me must only use symbols for its name. Note that the symbols are put between parentheses:
let (^||^) x y = x ** 2. + y ** 2.
We can now apply our infix operator:
let res = 2. ^||^ 3.
…which also gives 13. We can also chain our infix operators where the result of the first operation is applied to the second and then to the third and so on:
let res = 2. ^||^ 3. ^||^ 4. ^||^ 5.
…which yields 2856104.
View all F# related articles here.