Skip to content
Exercise · Functions as values · lesson 10 of 12

Exercise: accumulator

Write a function func makeAccumulator() (func(int) int, func()). It returns two functions that share one sum. The first is an accumulator: it adds its argument to the sum and returns the new sum. The second resets the sum to 0. The sum of each accumulator starts at 0.

  • add, reset := makeAccumulator(), then add(5) → 5
  • the next call add(3) → 8
  • after reset(), the call add(4) → 4

Constraints: the arguments are from -1000 to 1000 and may be negative or zero; each pair of functions created by a separate call to makeAccumulator has its own sum, and calls to one pair do not change another.

Do not add extra imports unless the task says so explicitly.

accumulator.go — go
go · 6 lines
Ctrl+Enter run · Esc leave editor

Subscribe to take the course

The course is free. Sign in with Telegram and subscribe to the channel to open every lesson.

Sign in another way