3. Selecting and transforming values
Collection traverses positions from first to last and binds that value once for each occurrence. The retention condition runs before the optional transformation.
Complete program
Define filter-twice-and-double as a function.
It accepts an integer sequence named input, an integer named threshold and another integer named other-threshold.
Collect the input values in encounter order into a fresh sequence. Retain each value only when it is greater than the threshold and it is greater than the other-threshold. Replace each retained value with the doubled value of that value before appending it.package generated
import (
"errors"
"math"
)
func FilterTwiceAndDouble(p0 []int64, p1 int64, p2 int64) ([]int64, error) {
result := make([]int64, 0)
for _, value := range p0 {
if value > p1 && value > p2 {
if value > math.MaxInt64/2 || value < math.MinInt64/2 {
return nil, errors.New("integer overflow")
}
result = append(result, value+value)
}
}
return result, nil
}1 is rejected. Each 4 and the 7 pass both ordered lower-bound checks and are doubled independently. The fresh destination therefore becomes [8,14,8] in encounter order.
Doubling is not a magical built-in attached to its English name. The installed vocabulary binds doubled value to the ordinary definition integer-double, whose body adds its input to itself using checked addition. Overflow is a runtime failure. A rejected occurrence is not transformed, so an overflowing value in a skipped branch is harmless.
Exercise
Use the same source with {"input":[-3,-2,0,5],"threshold":-3,"other-threshold":-2}. Predict the result before running it.
Verified solution
The retained values are 0 and 5; -3 and -2 fail a strict lower bound. The verified result is [0,10].