Course / The terminal and the language
Make a counter
How to fetch and submit this lab
Once: install the tool and connect your account.
curl -fsSL https://gonomicon.com/install.sh | sh
gonomicon loginEach lab: download it, edit the file named in the instructions, then submit.
gonomicon fetch week-1/12-07-make-counter
cd 12-07-make-counter
gonomicon submitGoal
Write MakeCounter, which returns a function that remembers a running count between calls, and MakeAdder, which returns a function that adds a fixed amount.
Example If you needed a machine that remembered the highest value it had ever seen, you'd build it the same way, with a variable outside the returned function:
func MakeHighWater() func(int) int {
best := 0
return func(n int) int {
if n > best {
best = n
}
return best
}
}
Rules
- Edit
counter.go. Both functions have a// TODOcomment and a return line you will change. MakeCountertakes nothing and returns a function that takes nothing and returns anint. Each call to that returned function should give the next count, starting at1.MakeAddertakes anint,n, and returns a function that takes anint,x, and returnsx + n.- Two separate calls to
MakeCountermust produce two counters that count independently of each other. The same goes for two separate calls toMakeAdderwith differentn. - Declare the counter's running total outside the returned function, the same way the lesson's
makeCounterdoes, so it survives between calls instead of resetting. - Do not change either function's signature.
What you'll practice Writing a closure that remembers state between calls, and one that just carries a fixed value along with it.
Run it
gonomicon fetch week-1/12-07-make-counter
cd 12-07-make-counter
gonomicon test
gonomicon submit
Hints
- MakeCounter needs a variable declared outside the returned function, so it survives between calls. Start it at 0, and inside the returned function increment it before returning it, so the first call gives 1.
- MakeAdder doesn't need any state at all: the returned function just reads n (its argument from MakeAdder) and x (its own argument) and adds them. A fresh call to MakeAdder makes a fresh, independent n.
- func MakeCounter() func() int { count := 0 return func() int { count++ return count } }
func MakeAdder(n int) func(int) int { return func(x int) int { return x + n } }