

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 5
click for more info
Not enough gems
Cost: 6 gems
1: Functions
incomplete
2: Multiple Parameters
incomplete
3: Unit Test Lessons
incomplete
4: Declaration Syntax
incomplete
5: Passing Variables by Value
incomplete
6: Ignoring Return Values
incomplete
7: Named Return Values
incomplete
8: The Benefits of Named Returns
incomplete
9: Explicit Returns
incomplete
10: Early Returns
incomplete
11: Functions As Values
incomplete
12: Anonymous Functions
incomplete
13: Defer
incomplete
14: Block Scope
incomplete
15: Processing Orders
incomplete
16: Closures
incomplete
17: Currying
incomplete
Back
ctrl+,
Next
ctrl+.
This lesson's interactive features are locked, please to keep using them
Go supports first-class and higher-order functions, which are just fancy ways of saying "functions as values". Functions are just another type -- like ints and strings and bools.
Let's assume we have two simple functions:
func add(x, y int) int {
return x + y
}
func mul(x, y int) int {
return x * y
}
We can create a new aggregate function that accepts a function as its 4th argument:
func aggregate(a, b, c int, arithmetic func(int, int) int) int {
firstResult := arithmetic(a, b)
secondResult := arithmetic(firstResult, c)
return secondResult
}
It calls the given arithmetic function (which could be add or mul, or any other function that accepts two ints and returns an int) and applies it to three inputs instead of two. It can be used like this:
func main() {
sum := aggregate(2, 3, 4, add)
// sum is 9
product := aggregate(2, 3, 4, mul)
// product is 24
}
Complete the reformat function. It takes a message string and a formatter function as input:
For example, if the message is "General Kenobi" and the formatter adds a period to the end of the string, the final result should be
TEXTIO: General Kenobi...