5 Functions and closures
Declare a function with Func. The calling function uses his name plus the argument list in parentheses. The name and return value type of the delimited parameter is used.
Func greet (name:string, day:string), String {
Return "Hello \ (name), today is \ (day)."
}
Greet ("Bob", "Tuesday")
Note
Practice
Remove the day parameter and add a parameter containing today's lunch selection.
Use tuple (tuple) to return multiple values.
Func getgasprices () (double, double, double) {
Return (3.59, 3.69, 3.79)
}
Getgasprices ()
The function can accept a variable number of parameters and collect it into an array.
Func sumof (Numbers:int ...), Int {
var sum = 0
For number in numbers {
Sum + = number
}
return sum
}
Sumof ()
Sumof (42, 597, 12)
Note
Practice
Write a function to calculate the average of its parameters.
Functions can be nested. Inline functions can access the variables of the function whose definition is located. You can use inline functions to organize your code to avoid too long and too complex.
Func Returnfifteen (), Int {
var y = 10
Func Add ()
{
Y + = 5
}
Add ()
Return y
}//by Gashero
Returnfifteen ()
The function is the first type. This means that the function can return another function.
Func Makeincrementer ()-(int-int) {
Func AddOne (number:int), Int {
Return 1 + number
}
Return AddOne
}
var increment = Makeincrementer ()
Increment (7)
A function can accept other functions as arguments.
Func hasanymatches (list:int[], condition:int-bool), BOOL {
For item in list {
If condition (item) {
return True
}
}
return False
}
Func Lessthanten (number:int), Bool {
Return number < 10
}
var numbers = [20, 19, 7, 12]
Hasanymatches (Numbers, Lessthanten)
The function is actually a special case of closures. You can write a closure without a name, just put it in curly braces. Use in to the return value of a specific parameter and body.
Numbers.map ({
(Number:int), Int in
Let result = 3 * number
return result
})
Note
Practice
Override a closed package to return 0 for all odd numbers.
There are several options for writing closures. When a closure type is known, such as a callback, you can ignore its arguments and return values, or both. A closure of a single statement can return a value directly.
Numbers.map ({number in 3 * number})
You can refer to a parameter by a number instead of a name, which is useful for very short closures. A closure passes its last argument to the function as the return value.
Sort ([1, 5, 3, 2]) {$ > $}