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.
Subscribe to take the course
The course is free. Sign in with Telegram and subscribe to the channel to open every lesson.