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

Exercise: filter

Write a function func filter(nums []int, keep func(int) bool) []int. It returns a new slice of those elements of nums for which keep returns true, in their original order. In the examples, isEven and isPositive are functions from the tests file: the first checks that a number is even, the second that it is greater than zero.

  • filter([]int{1, 2, 3, 4, 5, 6}, isEven) → [2 4 6]
  • filter([]int{-3, 0, 7, -1}, isPositive) → [7]
  • filter([]int{1, 3}, isEven) → []

Constraints: nums has from 0 to 1000 elements and may be empty or nil; if no element matches, the result is empty; the function does not change the slice nums itself.

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

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