Predicate-based functions
The first type of functions that we will explore is predicate-based functions. A predicate is a statement that can be evaluated as either true or false. Typically, in a language without a higher-order function, this would be achieved by using if
statements inside the body of a function. A common use case is to filter a set of data into a subset that matches a specific condition – for example, given a list of people, return all of those who are older than 18 years old.
To start, we can introduce a type alias for a function that defines the type signature of a predicate:
type Predicate[A any] func(A) bool
This type alias tells us that the function takes an input with a type of A
, which can represent the any
type in our program, but needs to return a bool
value. This type uses generics, which were introduced in Go 1.18. We can now use this type in every place at which a predicate is expected. The first function that works using predicates is the...