Function Declaration
func multiplyAdd(Float x, y, Int z) -> Float {
return x * y + Float(z)
}
Function declarations start with the keyword func, as in Swift.
Easier parsing due to clear distinction between function declaration vs. variable declaration, avoiding the most vexing parse.
Using the trailing return type syntax -> ReturnType.
Void functions (AKA “procedures”) are written without trailing :-> Void
func print(String line) { ... }
Function parameters are given as TypeName parameterName, multiple function parameters of the (exact) same type can be combined:
func multiply(Int x, y) -> Int // x and y are Int
Pure Functions
A pure function (punc) always produces the same output for the same inputs and has no observable side effects. It cannot modify external state or its arguments.
punc compoundInterest(Float capital, interestRate, Int years) -> Float
{
return capital * pow(1.0 + interestRate, years);
}
Lambdas
Lambdas also similar to C++
[](Int x) -> Float { x * 3.1415926535897931 }
Capture without Variable
| Syntax | Meaning |
|---|---|
[] |
Capture nothing |
[default] |
Capture all used variables by const copy or const reference depending on its type |
[copy] |
Capture all used variables by (mutable) copy |
[ref] |
Capture all used variables by reference |
[move] |
Move all used variables into the lambda |
Capture with Variable
| Syntax | Meaning |
|---|---|
[x] |
Const copy or const reference depending on x’s type |
[copy x] |
Capture x by (mutable) copy |
[ref x] |
Capture x by reference |
[move x] |
Move x into the lambda |
Capture this
| Syntax | Meaning |
|---|---|
[this] |
Capture the current object by const copy or const reference depending on its type |
[ref this] |
Capture the current object by reference |
[copy this] |
Capture the current object by (mutable) copy |
Misc
constMember Functionsclass MyArrayOfInt { const func size() -> Int { ... } }constexpr,constevalconstexpr multiply(Int x, y) -> Int { return x * y } consteval multiply(Int x, y) -> Int { return x * y }
Function Pointers
Trying to maintain consistency between declarations of functions, function pointers, functors and lambdas.
Examples:
func(Int, Int -> Int)* pointerToFunctionOfIntAndIntToIntfunc(Int)* pointerToFunctionOfIntfunc(Int, Int -> Int)& referenceToFunctionOfIntAndIntToInt// Can’t be zerofunc(Int)& referenceToFunctionOfInt
Function Parameters
By default, function arguments are passed as const reference. Only small types (with a size of up to 16 bytes) are passed as const value.
For details, see Parameter Passing.