Course outline
Course / The terminal and the language

Make a counter

Lab

How to fetch and submit this lab

Once: install the tool and connect your account.

curl -fsSL https://gonomicon.com/install.sh | sh
gonomicon login

Each 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 submit

Go installed? gonomicon test runs the visible test on your computer first. Submitting also runs hidden checks on our server.

Goal 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 // TODO comment and a return line you will change.
  • MakeCounter takes nothing and returns a function that takes nothing and returns an int. Each call to that returned function should give the next count, starting at 1.
  • MakeAdder takes an int, n, and returns a function that takes an int, x, and returns x + n.
  • Two separate calls to MakeCounter must produce two counters that count independently of each other. The same goes for two separate calls to MakeAdder with different n.
  • Declare the counter's running total outside the returned function, the same way the lesson's makeCounter does, 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

  1. 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.
  2. 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.
  3. 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 } }

Something wrong with this lesson? Report a problem