Functions are sequences of statements that perform a specific task. Functions have parameters (inputs) and an optional return value (output). Functions are typed: the function type consists of the parameter types and the return type.
Functions are values, i.e., they can be assigned to constants and variables, and can be passed as arguments to other functions. This behavior is often called "first-class functions".
Functions can be declared by using the fun
keyword, followed by the name of the declaration,
the parameters, the optional return type,
and the code that should be executed when the function is called.
The parameters need to be enclosed in parentheses.
The return type, if any, is separated from the parameters by a colon (:
).
The function code needs to be enclosed in opening and closing braces.
Each parameter must have a name, which is the name that the argument value will be available as within the function.
An additional argument label can be provided to require function calls to use the label to provide an argument value for the parameter.
Argument labels make code more explicit and readable. For example, they avoid confusion about the order of arguments when there are multiple arguments that have the same type.
Argument labels should be named so they make sense from the perspective of the function call.
Argument labels precede the parameter name.
The special argument label _
indicates
that a function call can omit the argument label.
If no argument label is declared in the function declaration,
the parameter name is the argument label of the function declaration,
and function calls must use the parameter name as the argument label.
Each parameter needs to have a type annotation, which follows the parameter name after a colon.
Function calls may provide arguments for parameters which are subtypes of the parameter types.
There is no support for optional parameters, i.e. default values for parameters, and variadic functions, i.e. functions that take an arbitrary amount of arguments.
1// Declare a function named `double`, which multiples a number by two.2//3// The special argument label _ is specified for the parameter,4// so no argument label has to be provided in a function call.5//6fun double(_ x: Int): Int {7return x * 28}910// Call the function named `double` with the value 4 for the first parameter.11//12// The argument label can be omitted in the function call as the declaration13// specifies the special argument label _ for the parameter.14//15double(2) // is `4`
It is possible to require argument labels for some parameters, and not require argument labels for other parameters.
1// Declare a function named `clamp`. The function takes an integer value,2// the lower limit, and the upper limit. It returns an integer between3// the lower and upper limit.4//5// For the first parameter the special argument label _ is used,6// so no argument label has to be given for it in a function call.7//8// For the second and third parameter no argument label is given,9// so the parameter names are the argument labels, i.e., the parameter names10// have to be given as argument labels in a function call.11//12fun clamp(_ value: Int, min: Int, max: Int): Int {13if value > max {14return max15}1617if value < min {18return min19}2021return value22}2324// Declare a constant which has the result of a call to the function25// named `clamp` as its initial value.26//27// For the first argument no label is given, as it is not required by28// the function declaration (the special argument label `_` is specified).29//30// For the second and this argument the labels must be provided,31// as the function declaration does not specify the special argument label `_`32// for these two parameters.33//34// As the function declaration also does not specify argument labels35// for these parameters, the parameter names must be used as argument labels.36//37let clamped = clamp(123, min: 0, max: 100)38// `clamped` is `100`
1// Declare a function named `send`, which transfers an amount2// from one account to another.3//4// The implementation is omitted for brevity.5//6// The first two parameters of the function have the same type, so there is7// a potential that a function call accidentally provides arguments in8// the wrong order.9//10// While the parameter names `senderAddress` and `receiverAddress`11// are descriptive inside the function, they might be too verbose12// to require them as argument labels in function calls.13//14// For this reason the shorter argument labels `from` and `to` are specified,15// which still convey the meaning of the two parameters without being overly16// verbose.17//18// The name of the third parameter, `amount`, is both meaningful inside19// the function and also in a function call, so no argument label is given,20// and the parameter name is required as the argument label in a function call.21//22fun send(from senderAddress: Address, to receivingAddress: Address, amount: Int) {23// The function code is omitted for brevity.24// ...25}2627// Declare a constant which refers to the sending account's address.28//29// The initial value is omitted for brevity.30//31let sender: Address = // ...3233// Declare a constant which refers to the receiving account's address.34//35// The initial value is omitted for brevity.36//37let receiver: Address = // ...3839// Call the function named `send`.40//41// The function declaration requires argument labels for all parameters,42// so they need to be provided in the function call.43//44// This avoids ambiguity. For example, in some languages (like C) it is45// a convention to order the parameters so that the receiver occurs first,46// followed by the sender. In other languages, it is common to have47// the sender be the first parameter, followed by the receiver.48//49// Here, the order is clear – send an amount from an account to another account.50//51send(from: sender, to: receiver, amount: 100)
The order of the arguments in a function call must match the order of the parameters in the function declaration.
1// Declare a function named `test`, which accepts two parameters, named `first` and `second`2//3fun test(first: Int, second: Int) {4// ...5}67// Invalid: the arguments are provided in the wrong order,8// even though the argument labels are provided correctly.9//10test(second: 1, first: 2)
Functions can be nested, i.e., the code of a function may declare further functions.
1// Declare a function which multiplies a number by two, and adds one.2//3fun doubleAndAddOne(_ x: Int): Int {45// Declare a nested function which multiplies a number by two.6//7fun double(_ x: Int) {8return x * 29}1011return double(x) + 112}1314doubleAndAddOne(2) // is `5`
Functions do not support overloading.
Functions can be also used as expressions. The syntax is the same as for function declarations, except that function expressions have no name, i.e., they are anonymous.
1// Declare a constant named `double`, which has a function as its value.2//3// The function multiplies a number by two when it is called.4//5// This function's type is `fun (Int): Int`.6//7let double =8fun (_ x: Int): Int {9return x * 210}
Functions can be annotated as view
to indicate that they do not modify any external state or any account state.
A view
annotation can be added to the beginning of a function declaration or expression like so:
1view pub fun foo(): Void {}2let x = view fun(): Void {}3pub struct S {4view pub fun foo(): Void {}5view init()6}
All functions that do not have a view
annotation are considered non-view,
and cannot be called inside of view
contexts,
like inside of a view
function or in a precondition or postcondition.
Function types can also have view
annotations,
to be placed after the opening parenthesis but before the parameter list.
So, for example, these are valid types:
1let f: view fun (Int): Int = ...2let h: view fun (): (view fun (): Void) = ...
Any function types without a view
annotation will be considered non-view.
Functions are covariant with respect to view
annotations,
so a view
function is a subtype of an non-view function with the same parameters and return types.
So, the following declarations would typecheck:
1let a: view fun (): Void = view fun() {}2let b: fun (): Void = view fun() {}3let c: fun (): Void = fun() {}4let d: fun(view fun(): Void): Void = fun (x: fun(): Void) {} // contravariance
while these would not:
1let x: view fun (): Void = fun() {}2let y: fun(fun(): Void): Void = fun(f: view fun(): Void) {} // contravariance
The operations that are not permitted in view
contexts are:
- Calling a non-view function (including any functions that modify account state or storage like
save
orload
) - Writing to or modifying any resources
- Writing to or modifying any references
- Indexed assignment or writes to any variables not statically knowable to have been defined in the current function's scope, or to any resources or references
So, for example, this code would be allowed:
1view fun foo(): Int {2let a: [Int] = []3a[0] = 34return a.length5}
while this would not:
1let a: [Int] = []2view fun foo(): Int {3a[0] = 34return a.length5}
A caveat to this is that in some cases a non-view
function that only performs a mutation that would be allowed in a view
context will be rejected as a limitation of the analysis.
In particular, users may encounter this with arrays or dictionaries, where a function like:
1view fun foo(): Int {2let a: [Int] = [0]3a[0] = 14}
is acceptable, because a
is local to this function, while
1view fun foo(): Int {2let a: [Int] = [0]3a.append(1)4}
will be rejected, because append
is not view
.
Functions can be called (invoked). Function calls need to provide exactly as many argument values as the function has parameters.
1fun double(_ x: Int): Int {2return x * 23}45// Valid: the correct amount of arguments is provided.6//7double(2) // is `4`89// Invalid: too many arguments are provided.10//11double(2, 3)1213// Invalid: too few arguments are provided.14//15double()
Function types consist of the function's parameter types and the function's return type.
The parameter types need to be enclosed in parentheses,
followed by a colon (:
), and end with the return type.
The whole function type needs to be enclosed in parentheses.
1// Declare a function named `add`, with the function type `fun(Int, Int): Int`.2//3fun add(a: Int, b: Int): Int {4return a + b5}
1// Declare a constant named `add`, with the function type `fun(Int, Int): Int`2//3let add: fun(Int, Int): Int =4fun (a: Int, b: Int): Int {5return a + b6}
If the function has no return type, it implicitly has the return type Void
.
1// Declare a constant named `doNothing`, which is a function2// that takes no parameters and returns nothing.3//4let doNothing: fun(): Void =5fun () {}
Parentheses also control precedence.
For example, a function type fun(Int): fun(): Int
is the type
for a function which accepts one argument with type Int
,
and which returns another function,
that takes no arguments and returns an Int
.
The type [fun(Int): Int; 2]
specifies an array type of two functions,
which accept one integer and return one integer.
Argument labels are not part of the function type. This has the advantage that functions with different argument labels, potentially written by different authors are compatible as long as the parameter types and the return type match. It has the disadvantage that function calls to plain function values, cannot accept argument labels.
1// Declare a function which takes one argument that has type `Int`.2// The function has type `fun(Int): Void`.3//4fun foo1(x: Int) {}56// Call function `foo1`. This requires an argument label.7foo1(x: 1)89// Declare another function which takes one argument that has type `Int`.10// The function also has type `fun(Int): Void`.11//12fun foo2(y: Int) {}1314// Call function `foo2`. This requires an argument label.15foo2(y: 2)1617// Declare a variable which has type `fun(Int): Void` and use `foo1`18// as its initial value.19//20var someFoo: fun(Int): Void = foo12122// Call the function assigned to variable `someFoo`.23// This is valid as the function types match.24// This does neither require nor allow argument labels.25//26someFoo(3)2728// Assign function `foo2` to variable `someFoo`.29// This is valid as the function types match.30//31someFoo = foo23233// Call the function assigned to variable `someFoo`.34// This does neither require nor allow argument labels.35//36someFoo(4)
A function may refer to variables and constants of its outer scopes in which it is defined. It is called a closure, because it is closing over those variables and constants. A closure can read from the variables and constants and assign to the variables it refers to.
1// Declare a function named `makeCounter` which returns a function that2// each time when called, returns the next integer, starting at 1.3//4fun makeCounter(): fun(): Int {5var count = 06return fun (): Int {7// NOTE: read from and assign to the non-local variable8// `count`, which is declared in the outer function.9//10count = count + 111return count12}13}1415let test = makeCounter()16test() // is `1`17test() // is `2`
When arguments are passed to a function, they are copied. Therefore, values that are passed into a function are unchanged in the caller's scope when the function returns. This behavior is known as call-by-value.
1// Declare a function that changes the first two elements2// of an array of integers.3//4fun change(_ numbers: [Int]) {5// Change the elements of the passed in array.6// The changes are only local, as the array was copied.7//8numbers[0] = 19numbers[1] = 210// `numbers` is `[1, 2]`11}1213let numbers = [0, 1]1415change(numbers)16// `numbers` is still `[0, 1]`
Parameters are constant, i.e., it is not allowed to assign to them.
1fun test(x: Int) {2// Invalid: cannot assign to a parameter (constant)3//4x = 25}
Functions may have preconditions and may have postconditions. Preconditions and postconditions can be used to restrict the inputs (values for parameters) and output (return value) of a function.
Preconditions must be true right before the execution of the function.
Preconditions are part of the function and introduced by the pre
keyword,
followed by the condition block.
Postconditions must be true right after the execution of the function.
Postconditions are part of the function and introduced by the post
keyword,
followed by the condition block.
Postconditions may only occur after preconditions, if any.
A conditions block consists of one or more conditions. Conditions are expressions evaluating to a boolean.
Conditions may be written on separate lines, or multiple conditions can be written on the same line, separated by a semicolon. This syntax follows the syntax for statements.
Following each condition, an optional description can be provided after a colon. The condition description is used as an error message when the condition fails.
In postconditions, the special constant result
refers to the result of the function.
1fun factorial(_ n: Int): Int {2pre {3// Require the parameter `n` to be greater than or equal to zero.4//5n >= 0:6"factorial is only defined for integers greater than or equal to zero"7}8post {9// Ensure the result will be greater than or equal to 1.10//11result >= 1:12"the result must be greater than or equal to 1"13}1415if n < 1 {16return 117}1819return n * factorial(n - 1)20}2122factorial(5) // is `120`2324// Run-time error: The given argument does not satisfy25// the precondition `n >= 0` of the function, the program aborts.26//27factorial(-2)
In postconditions, the special function before
can be used
to get the value of an expression just before the function is called.
1var n = 023fun incrementN() {4post {5// Require the new value of `n` to be the old value of `n`, plus one.6//7n == before(n) + 1:8"n must be incremented by 1"9}1011n = n + 112}
Both preconditions and postconditions are considered view
contexts;
any operations that are not legal in functions with view
annotations are also not allowed in conditions.
In particular, this means that if you wish to call a function in a condition, that function must be view
.
Functions are values ("first-class"), so they may be assigned to variables and fields or passed to functions as arguments.
1// Declare a function named `transform` which applies a function to each element2// of an array of integers and returns a new array of the results.3//4pub fun transform(function: fun(Int): Int, integers: [Int]): [Int] {5var newIntegers: [Int] = []6for integer in integers {7newIntegers.append(function(integer))8}9return newIntegers10}1112pub fun double(_ integer: Int): Int {13return integer * 214}1516let newIntegers = transform(function: double, integers: [1, 2, 3])17// `newIntegers` is `[2, 4, 6]`