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

★ Exercise: repeat a function

Write func repeat(f func(int) int, n int) func(int) int. It returns a function that applies f to its argument n times in a row: repeat(f, 3)(x) is f(f(f(x))).

  • repeat(inc, 3)(10) → 13, where inc adds one
  • repeat(double, 4)(1) → 16, where double doubles
  • repeat(double, 0)(7) → 7

Constraints: n is from 0 to 1000; repeat itself never calls f — only the returned function does; that function may be called many times, and each call applies f exactly n times.

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

repeat.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